package sdk.webview.fmc.com.fmcsdk.check.activity;

import static sdk.webview.fmc.com.fmcsdk.activity.H5Activity.EVENT_BUS_NOTIFY_H5_BACK;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.MediaController;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import sdk.webview.fmc.com.fmcsdk.BaoTipEvent;
import sdk.webview.fmc.com.fmcsdk.R;
import sdk.webview.fmc.com.fmcsdk.activity.CameraOneActivity;
import sdk.webview.fmc.com.fmcsdk.activity.CaptureActivity;
import sdk.webview.fmc.com.fmcsdk.activity.H5Activity;
import sdk.webview.fmc.com.fmcsdk.activity.H5ForNfcActivity;
import sdk.webview.fmc.com.fmcsdk.activity.HomeH5Event;
import sdk.webview.fmc.com.fmcsdk.activity.ImageEditActivity;
import sdk.webview.fmc.com.fmcsdk.activity.RecordVideoActivity;
import sdk.webview.fmc.com.fmcsdk.app.AppManager;
import sdk.webview.fmc.com.fmcsdk.app.FMCApplication;
import sdk.webview.fmc.com.fmcsdk.base.BaseActivity;
import sdk.webview.fmc.com.fmcsdk.base.BindEventBus;
import sdk.webview.fmc.com.fmcsdk.base.UserApi;
import sdk.webview.fmc.com.fmcsdk.bean.GETREPORTBean;
import sdk.webview.fmc.com.fmcsdk.bean.GetManagerBean;
import sdk.webview.fmc.com.fmcsdk.bean.OperateReportBean;
import sdk.webview.fmc.com.fmcsdk.bean.UploadImage;
import sdk.webview.fmc.com.fmcsdk.camera.BitmapUtils;
import sdk.webview.fmc.com.fmcsdk.check.CacheHelper;
import sdk.webview.fmc.com.fmcsdk.check.NfcCodeEvent;
import sdk.webview.fmc.com.fmcsdk.check.UpdataPoint;
import sdk.webview.fmc.com.fmcsdk.check.adapter.ImagePagerAdapter;
import sdk.webview.fmc.com.fmcsdk.check.adapter.ShutDownAdapter;
import sdk.webview.fmc.com.fmcsdk.check.adapter.WorkStartAdapter;
import sdk.webview.fmc.com.fmcsdk.check.bean.ActivityJsonBean;
import sdk.webview.fmc.com.fmcsdk.check.bean.GetDetailsBean;
import sdk.webview.fmc.com.fmcsdk.check.bean.ImageSelectBean;
import sdk.webview.fmc.com.fmcsdk.check.bean.RunListPagerBean;
import sdk.webview.fmc.com.fmcsdk.check.bean.StartEmptyEvent;
import sdk.webview.fmc.com.fmcsdk.check.dialog.BottomPopupWindow;
import sdk.webview.fmc.com.fmcsdk.check.dialog.CenterPopupWindow;
import sdk.webview.fmc.com.fmcsdk.check.interfaces.StartWorkView;
import sdk.webview.fmc.com.fmcsdk.check.listener.OnCameraPhotoListener;
import sdk.webview.fmc.com.fmcsdk.check.listener.RequestPermissionsListener;
import sdk.webview.fmc.com.fmcsdk.check.listener.StartH5Event;
import sdk.webview.fmc.com.fmcsdk.check.listener.UpDateStatusEvent;
import sdk.webview.fmc.com.fmcsdk.check.persenter.StartWorkPersenter;
import sdk.webview.fmc.com.fmcsdk.db.DatabaseManager;
import sdk.webview.fmc.com.fmcsdk.imagepicker.utils.Utils;
import sdk.webview.fmc.com.fmcsdk.service.UploadEventLoad;
import sdk.webview.fmc.com.fmcsdk.upload.ImageUploadBean;
import sdk.webview.fmc.com.fmcsdk.util.Constant;
import sdk.webview.fmc.com.fmcsdk.util.DateUtil;
import sdk.webview.fmc.com.fmcsdk.util.DesUtil;
import sdk.webview.fmc.com.fmcsdk.util.FastClickHelper;
import sdk.webview.fmc.com.fmcsdk.util.FastClickHelperClick;
import sdk.webview.fmc.com.fmcsdk.util.FileUtil;
import sdk.webview.fmc.com.fmcsdk.util.GsonUtil;
import sdk.webview.fmc.com.fmcsdk.util.HandleJsEvent;
import sdk.webview.fmc.com.fmcsdk.util.ImageCompressor;
import sdk.webview.fmc.com.fmcsdk.util.ImageUtils;
import sdk.webview.fmc.com.fmcsdk.util.KLog;
import sdk.webview.fmc.com.fmcsdk.util.NetworkUtils;
import sdk.webview.fmc.com.fmcsdk.util.SnackBarUtil;
import sdk.webview.fmc.com.fmcsdk.util.SoftKeyBoardListener;
import sdk.webview.fmc.com.fmcsdk.util.StringUtils;
import sdk.webview.fmc.com.fmcsdk.util.ToastUtils;
import sdk.webview.fmc.com.fmcsdk.util.Url;
import sdk.webview.fmc.com.fmcsdk.util.UserHelper;
import sdk.webview.fmc.com.fmcsdk.util.Utility;
import sdk.webview.fmc.com.fmcsdk.util.retrofit2.observer.ResponseTransformer;
import sdk.webview.fmc.com.fmcsdk.util.retrofit2.subscriber.ResponseSubscriber;
import sdk.webview.fmc.com.fmcsdk.view.CreamOrVideoRecordDialog;
import top.zibin.luban.OnCompressListener;

@BindEventBus
public class StartWorkActivity extends BaseActivity<StartWorkView, StartWorkPersenter> implements StartWorkView {


    private static final Logger log = LoggerFactory.getLogger(StartWorkActivity.class);
    private RecyclerView mRvStart;


    private WorkStartAdapter startWorkAdapter;


    private RunListPagerBean runListPagerBean;

    private GetDetailsBean getDetailsBean;
    private String assetId, projId, detailId;

    private TextView tvTitle;
    private FrameLayout mFlLeft;
    private TextView mTvNum;
    private TextView mTvAllNum;
    private FrameLayout mFlRight;
    private TextView mTvName;
    private CheckBox mCbView;
    private LinearLayout mLlJiankang;
    private TextView mTvStop;
    private TextView mTvStatus;
    private LinearLayout mLlHealth;
    private TextView tvSubmitCheck, tvBack;
    private LinearLayout llHaveWork, llNotHavaWork;
    private ImageView ivLeft;
    private LinearLayout llRunCheckCard;

    private LinearLayout ll_all_normal, ll_show_un, ll_show, ll_device_health_card_error, ll_base;
    private ImageView iv_all_normal, iv_show_un;

    private TextView tv_have_error;

    private LinearLayout ll_empty;
    private int selectPosition;
    private GetDetailsBean.RecordDTO.PointsDTO pointsDTO;

    //检测列表
    // private上传图片 List<GetDetailsBean.RecordDTO.PointsDTO.CheckListDTO> checkList = new ArrayList<>();
    private List<GetDetailsBean.RecordDTO.PointsDTO.CheckListDTO> submitCheckList = new ArrayList();
    private List<ImageSelectBean> recordList = new ArrayList<>();

    //当前检查的节点
    private int currentPointPosition = 0;

    private BottomPopupWindow bottomPopupWindow, abnormalPopupWindow;


    private static final int IMAGEEDIT_OK = 19;

    private DatabaseManager databaseManager;
    private String managerName, managerPhone, managerId;
    private String pointId;

    private static final int RECORDVIDEO = 20;

    private static final int WATER_MATER_SETTING = 22;
    private boolean isShowUnChane = false, isAllNormal = false;
    private String videoId = "";
    private String recordType = "";
    private String workOrderId = "";

//    private boolean isMustWorkOrder = false;
//    private String[] needOrder = {"2", "4", "5", "6"};
//    private String[] workTicket = {"1", "3 ", "5", "6"};
//    private String[] saveNotOrder = {"3", "4", "6"};

    private boolean isClickShutDown = false;

    private GetDetailsBean.RecordDTO.PointsDTO.CheckListDTO recordItem = null;
    private int recordPosition = -1;

    private LinearLayout ll_lixian, ll_zai;
    private String pointCheckId;//巡检项目id
    private boolean isScanOk = true;

    private boolean isFromFirst = true;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_start_work;
    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        // EventBus.getDefault().post(new HomeH5Event());
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        // 在 Activity 的 onCreate() 方法中设置状态栏颜色
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.setStatusBarColor(ContextCompat.getColor(this, R.color.color_DC3C26)); // 设置状态栏颜色
        }
        initView();
        initRecycler();
        initListener();
        initData();
        if (getDetailsBean == null || getDetailsBean.getRecord() == null) {
            finish();
            return;
        }
        presenter.getManager(getDetailsBean.getRecord().getStaffTeamId());

        //查看设备健康卡是否有异常
        presenter.getRunListPager(assetId, "5");


//        requestApi();

//        ActivityJsonBean bean = new DatabaseManager(context).getUserByName(getClass().getSimpleName());
//        if (bean != null) {
//            if (!TextUtils.isEmpty(bean.getJson())) {
//                runListPagerBean = GsonUtil.GsonToBean(bean.getJson(), RunListPagerBean.class);
//                getRunListPager(runListPagerBean);
//            }
//        }
        if (!NetworkUtils.isAvailable(context)) {
            hideLoading();
            ll_zai.setVisibility(View.GONE);
            ll_lixian.setVisibility(View.VISIBLE);
        }

        SoftKeyBoardListener.setListener(StartWorkActivity.this, new SoftKeyBoardListener.OnSoftKeyBoardChangeListener() {
            @Override
            public void keyBoardShow(int height) {
                if (view_bootom != null) {
                    view_bootom.setVisibility(View.VISIBLE);
                }
                if (view_bootom_sik != null) {
                    view_bootom_sik.setVisibility(View.VISIBLE);
                }
                KLog.e("show");
            }

            @Override
            public void keyBoardHide(int height) {
                if (view_bootom != null) {
                    view_bootom.setVisibility(View.GONE);
                }
                if (view_bootom_sik != null) {
                    view_bootom_sik.setVisibility(View.GONE);
                }

                KLog.e("dismiss");
            }
        });
    }


    private void initView() {
        ll_lixian = findViewById(R.id.ll_lixian);
        ll_zai = findViewById(R.id.ll_zai);
        ll_base = findViewById(R.id.ll_base);
        tvTitle = findViewById(R.id.tv_title);
        mFlLeft = findViewById(R.id.fl_left);
        mTvNum = findViewById(R.id.tv_num);
        mTvAllNum = findViewById(R.id.tv_all_num);
        mFlRight = findViewById(R.id.fl_right);
        mTvName = findViewById(R.id.tv_name);
        mCbView = findViewById(R.id.cb_view);
        mLlJiankang = findViewById(R.id.ll_jiankang);
        mTvStop = findViewById(R.id.tv_stop);
        mTvStatus = findViewById(R.id.tv_status);
        mLlHealth = findViewById(R.id.ll_health);
        tvSubmitCheck = findViewById(R.id.tv_submit_check);
        tvBack = findViewById(R.id.tv_back);
        llHaveWork = findViewById(R.id.ll_have_work);
        llNotHavaWork = findViewById(R.id.ll_not_hava_work);
        ivLeft = findViewById(R.id.iv_left);
        llRunCheckCard = findViewById(R.id.ll_run_check_card);

        ll_all_normal = findViewById(R.id.ll_all_normal);
        ll_show_un = findViewById(R.id.ll_show_un);
        iv_all_normal = findViewById(R.id.iv_all_normal);
        iv_show_un = findViewById(R.id.iv_show_un);
        ll_show = findViewById(R.id.ll_show);
        ll_device_health_card_error = findViewById(R.id.ll_device_health_card_error);
        tv_have_error = findViewById(R.id.tv_have_error);
        ll_empty = findViewById(R.id.ll_empty);
    }

    private void initRecycler() {
        mRvStart = findViewById(R.id.rv_start);
        mRvStart.setLayoutManager(new LinearLayoutManager(context));
        startWorkAdapter = new WorkStartAdapter(R.layout.item_start_work, new OnCameraPhotoListener() {
            @Override
            public void cameraPhotoListener(int position, String id) {
                selectPosition = position;
                pointCheckId = id;
                showCreamOrRecordVideoDialog();
            }

            @Override
            public void photoShowListener(int position, List<ImageSelectBean> list) {
                if (list.get(position).getImg().contains("mp4")) {
                    Intent intent = new Intent(context, VideoPlaybackActivity.class);
                    intent.putExtra("videoUrl", list.get(position).getImg());
                    startActivity(intent);
                    //showCenterPopupWindowPlayVideo(mLlHealth, list.get(position).getImg());
                } else {
                    showCenterPopupWindow(mLlHealth, position, list);
                }

            }
        });

        startWorkAdapter.setEmptyView(View.inflate(context, R.layout.empty_start_work, null));
        startWorkAdapter.setOnWorkStartAdapterChildClickListener(new WorkStartAdapter.OnWorkStartAdapterChildClickListener() {
            @Override
            public void onRemakeClick(int position) {
                GetDetailsBean.RecordDTO.PointsDTO.CheckListDTO item = startWorkAdapter.getItem(position);
                item.setBei(!item.isBei());
                startWorkAdapter.notifyItemChanged(position);
                //isShowEmpty(position);
            }

            @Override
            public void onPictureClick(int position) {
                GetDetailsBean.RecordDTO.PointsDTO.CheckListDTO item = startWorkAdapter.getItem(position);
                item.setCamera(!item.isCamera());
                startWorkAdapter.notifyItemChanged(position);
                //isShowEmpty(position);

            }

            @Override
            public void onNormalClick(int position, String checkResult) {
                GetDetailsBean.RecordDTO.PointsDTO.CheckListDTO item = startWorkAdapter.getItem(position);
                if (null != item) {
                    //如果备注或者拍照是必填 而且其中有一项确实是空的  需要设置他们为未检
                    if ((item.getMustFillRemark() != 0 && StringUtils.isEmpty(item.getRemark())) ||
                            (item.getMustTakePic() != 0 && item.getPictureUrls().isEmpty())) {
                        item.setChecked(0);
                    } else {
                        item.setChecked(1);
                    }
                    item.setCheckResult(checkResult);
                    startWorkAdapter.notifyItemChanged(position);
                }

            }

            @Override
            public void onErrorClick(View view, int position) {
                GetDetailsBean.RecordDTO.PointsDTO.CheckListDTO item = startWorkAdapter.getItem(position);
                if (null != item) {
                    showErrorDialog(view, item, position);
                }
            }

            @Override
            public void onPictureRemoveClick(int groupPosition, int position) {
                CenterPopupWindow centerPopupWindow = new CenterPopupWindow(context, R.layout.dialog_center_tip);
                TextView tvContent = centerPopupWindow.getContentView().findViewById(R.id.tv_content);
                centerPopupWindow.getContentView().findViewById(R.id.iv_close).setOnClickListener(v -> {
                    centerPopupWindow.dismiss();
                });
                tvContent.setText(context.getResources().getString(R.string.Are_you_sure_you_want_to_delete_the_picture));
                if (startWorkAdapter != null) {
                    String url = startWorkAdapter.getItem(groupPosition).getPictureUrls().get(position).getUrl();
                    if (url.contains("mp4")) {
                        tvContent.setText(context.getResources().getString(R.string.Are_you_sure_you_want_to_delete_the_video));
                    } else {
                        tvContent.setText(context.getResources().getString(R.string.Are_you_sure_you_want_to_delete_the_picture));
                    }
                }
                TextView tvCancel = centerPopupWindow.getContentView().findViewById(R.id.tv_cancel);
                TextView tvSure = centerPopupWindow.getContentView().findViewById(R.id.tv_sure);
                tvCancel.setOnClickListener(view1 -> centerPopupWindow.dismiss());
                tvSure.setOnClickListener(v -> {
                    String id = startWorkAdapter.getItem(groupPosition).getPictureUrls().get(position).getId();
                    if (NetworkUtils.isAvailable(context)) {
                        presenter.deletePic(id, groupPosition, position);
                    } else {
                        deletePicSuccess(groupPosition, position);
                    }
                    centerPopupWindow.dismiss();
                });
                centerPopupWindow.show(mRvStart);
            }

            @Override
            public void onEnterWaterMeterClick(int position) {
                GetDetailsBean.RecordDTO.PointsDTO.CheckListDTO item = startWorkAdapter.getItem(position);
                Intent intent = new Intent(context, WaterMeterActivity.class);
                intent.putExtra("data", GsonUtil.BeanToJson(item));
                intent.putExtra("pointsDTO", GsonUtil.BeanToJson(pointsDTO));
                intent.putExtra("getDetailsBean", GsonUtil.BeanToJson(getDetailsBean));
                intent.putExtra("detailId", detailId);
                intent.putExtra("assetId", assetId);
                intent.putExtra("projId", projId);
                intent.putExtra("pointId", pointId);
                intent.putExtra("managerName", managerName);
                intent.putExtra("managerPhone", managerPhone);
                intent.putExtra("managerId", managerId);
                intent.putExtra("listId", getDetailsBean.getRecord().getId());
                intent.putExtra("position", position);
                intent.putExtra("des", getDetailsBean.getRecord().getDescription());
                //intent.putExtra("isMustWorkOrder", isMustWorkOrder);
                startActivityForResult(intent, WATER_MATER_SETTING);
            }

            @Override
            public void onInputWaterMeterValueClick(View view, String value, int position) {
                GetDetailsBean.RecordDTO.PointsDTO.CheckListDTO item = startWorkAdapter.getItem(position);
                if (null != item) {
                    item.setMeterRead(value);
                    if (TextUtils.isEmpty(value) || TextUtils.equals(value, ".")) return;//设置抄表值
                    BigDecimal bigValue = new BigDecimal(value);
                    if (null != item.getAlertLowLimit()) {
                        if (bigValue.compareTo(item.getAlertLowLimit()) < 0) {
                            showErrorDialog(view, item, position);
                            return;
                        }
                    }


                    if (null != item.getAlertUpLimit()) {
                        if (bigValue.compareTo(item.getAlertUpLimit()) > 0) {
                            showErrorDialog(view, item, position);
                            return;
                        }
                    }

                    //此处就是正常
                    if ((item.getMustFillRemark() != 0 && StringUtils.isEmpty(item.getRemark())) ||
                            (item.getMustTakePic() != 0 && item.getPictureUrls().isEmpty())) {  //有必填项未填
                        item.setChecked(0);
                    } else {
                        item.setChecked(1);
                    }
                    item.setAbnormal(0);
                    startWorkAdapter.notifyItemChanged(position);
                }
            }

            @Override
            public void onStandardNameClick(String value, int position, View v) {
                CenterPopupWindow centerPopupWindow = new CenterPopupWindow(context, R.layout.dialog_content_tip);
                TextView tvContent = centerPopupWindow.getContentView().findViewById(R.id.tv_content);
                tvContent.setText(value);
                TextView tvClose = centerPopupWindow.getContentView().findViewById(R.id.tv_close);
                ImageView ivClose = centerPopupWindow.getContentView().findViewById(R.id.iv_close);

                tvClose.setOnClickListener(view1 -> {
                    centerPopupWindow.dismiss();

                });
                ivClose.setOnClickListener(view2 -> {
                    centerPopupWindow.dismiss();
                });
                centerPopupWindow.show(v);
            }
        });
        mRvStart.setAdapter(startWorkAdapter);
        mRvStart.setItemAnimator(null);
        startWorkAdapter.bindToRecyclerView(mRvStart);
        startWorkAdapter.setEmptyView(View.inflate(context, R.layout.layout_empty, null));

        startWorkAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
            @Override
            public void onChanged() {
                super.onChanged();
                //
                KLog.e("数据整体变化时回调");
                isShowEmpty();
            }

            @Override
            public void onItemRangeChanged(int positionStart, int itemCount) {
                super.onItemRangeChanged(positionStart, itemCount);
                // 数据范围变化时回调
                KLog.e("数据范围变化时回调");
                isShowEmpty();
            }

            @Override
            public void onItemRangeInserted(int positionStart, int itemCount) {
                super.onItemRangeInserted(positionStart, itemCount);
                // 数据插入时回调
                KLog.e("数据插入时回调");
            }

            @Override
            public void onItemRangeRemoved(int positionStart, int itemCount) {
                super.onItemRangeRemoved(positionStart, itemCount);
                // 数据移除时回调
                KLog.e("数据移除时回调");
            }

            @Override
            public void onItemRangeMoved(int fromPosition, int toPosition, int itemCount) {
                super.onItemRangeMoved(fromPosition, toPosition, itemCount);
                // 数据移动时回调
                KLog.e("数据移动时回调");

            }
        });

    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (v instanceof EditText) {
                Rect outRect = new Rect();
                v.getGlobalVisibleRect(outRect);
                // 判断点击是否在 EditText 区域外
                if (!outRect.contains((int) event.getRawX(), (int) event.getRawY())) {
                    v.clearFocus();  // 清除焦点
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    if (imm != null) {
                        imm.hideSoftInputFromWindow(v.getWindowToken(), 0);  // 隐藏软键盘
                    }
                }
            }
        }
        return super.dispatchTouchEvent(event);
    }

    private void showErrorDialog(View view, GetDetailsBean.RecordDTO.PointsDTO.CheckListDTO item, int position) {
        showAbnormalPopupWindow(view, item, new OnAbnormalPopupWindowListener() {
            @Override
            public void OnSaveNoDeclarationClick(String content) {
                item.setRemark(content);
                if (item.getHasMeter() == 1) {
                    if ((item.getMustFillRemark() != 0 && StringUtils.isEmpty(item.getRemark())) ||
                            (item.getMustTakePic() != 0 && item.getPictureUrls().isEmpty())) {
                        item.setChecked(0);
                    } else {
                        item.setChecked(1);
                    }
                    item.setAbnormal(1);
                } else {
                    //保存不报单的情况下  如果有必填项 但是没有填  也是算作未检
                    if ((item.getMustFillRemark() != 0 && StringUtils.isEmpty(item.getRemark())) ||
                            (item.getMustTakePic() != 0 && item.getPictureUrls().isEmpty())) {
                        item.setChecked(0);
                    } else {
                        item.setChecked(1);
                    }
                    item.setCheckResult("N1");
                }
                item.setRemark(content);
                startWorkAdapter.notifyItemChanged(position);
            }

            @Override
            public void onWorkTickClick(String content, String inspectionItemId, boolean isMust) {
                String baseUrl = PreferenceManager.getDefaultSharedPreferences(context).getString(Constant.BASE_ADDRESS_URL, "");
                Map<String, String> paramsMap = new HashMap<>();
                paramsMap.put("orderId", detailId);
                paramsMap.put("pointId", pointsDTO.getId());
                paramsMap.put("taskId", presenter.getSharedPrefs().getString("taskId", ""));
                paramsMap.put("type", "inspChecklist");
                paramsMap.put("fromOrderId", pointsDTO.getOrderId());
                paramsMap.put("planPointId", pointsDTO.getPlanPointId());

                String url = "";
                String isLine = sharedPrefs.getString(Constant.OPEN_OFFLINE_MODE, "0");
                Log.e("isLine", isLine + "");
                if (NetworkUtils.isAvailable(StartWorkActivity.this)) {
                    url = "#/srtask/apply";
                } else {
                    url = "#/srtask/offlinerepair";
                }
                String debug = "";
                if (sharedPrefs.getBoolean(Constant.OPEN_START_MODE, false)) {
                    debug = "&isdebug=true";
                }

                String remake = "";
                String locationDesc = "";
                String assetDesc = "";
                String serviceTypeDesc = "";
                String workerDesc = "";
                try {
                    remake = URLEncoder.encode("<" + item.getTitle() + ">" + getResources().getString(R.string.Find_an_anomaly) + "。" + content, "UTF-8");
                    locationDesc = URLEncoder.encode(pointsDTO.getLocationDesc(), "UTF-8");
                    assetDesc = URLEncoder.encode(pointsDTO.getAssetDesc(), "UTF-8");
                    serviceTypeDesc = URLEncoder.encode((StringUtils.isEmpty(getDetailsBean.getRecord().getSysServiceTypeDesc()) ? "" : getDetailsBean.getRecord().getSysServiceTypeDesc()), "UTF-8");
                    workerDesc = URLEncoder.encode((StringUtils.isEmpty(getDetailsBean.getRecord().getReportWorkerDesc()) ? "" : getDetailsBean.getRecord().getReportWorkerDesc()), "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    throw new RuntimeException(e);
                }

                String h5Url = baseUrl + "/h5/mytask/" + "?accessToken=" + UserHelper.getToken() + debug + url + "?assetId=" + assetId +
                        "&locationId=" + (StringUtils.isEmpty(pointsDTO.getLocationId()) ? "" : pointsDTO.getLocationId()) +
                        "&projId=" + projId +
                        "&locationDesc=" + locationDesc +
                        "&assetDesc=" + assetDesc +
                        "&description=" + remake +
                        "&questionDesc=" + remake +
                        "&requireType=SR&href=" + GsonUtil.BeanToJson(paramsMap) +
                        "&type=insp_check&requestWay=INSP_REPORT_1&staffTeamId=" + getDetailsBean.getRecord().getReportStaffTeamId() +
                        "&StaffTeamDesc=&workerId=" + (StringUtils.isEmpty(getDetailsBean.getRecord().getReportWorkerId()) ? "" : getDetailsBean.getRecord().getReportWorkerId()) +
                        "&workerDesc=" + workerDesc +
                        "&serviceTypeProjId=" + (StringUtils.isEmpty(getDetailsBean.getRecord().getReportServiceTypeId()) ? "" : getDetailsBean.getRecord().getReportServiceTypeId()) +
                        "&serviceTypeDesc=" + serviceTypeDesc +
                        "&gjId=" + detailId +
                        "&orderChklistId=" + item.getId() +
                        "&backRepair=3&inspDetailID=" + inspectionItemId +
                        "&from=app&imageList=" + new Gson().toJson(item.getPictureUrls()) +
                        "&formOrderId=" + pointsDTO.getOrderId() +
                        "&planPointId=" + pointsDTO.getPlanPointId();

                KLog.e(GsonUtil.BeanToJson(item.getPictureUrls()));


                CacheHelper.getInstance().addNoNetImage(item.getPictureUrls());

                item.setRemark(content);
                if (!isMust) {  // isMust 是报单必填 也就是说当前的报工单 里面的内容必须填完 （在没有备注或者拍照必填项的情况下  才能算作是已检） （如果有拍照或者备注的必填项  但是没有填完 也不能算作是已检）
                    if (item.getHasMeter() == 1) {  //抄表的逻辑
                        item.setAbnormal(1);
                        if ((item.getMustFillRemark() != 0 && StringUtils.isEmpty(item.getRemark())) ||
                                (item.getMustTakePic() != 0 && item.getPictureUrls().isEmpty())) { //有必填项未填
                            item.setChecked(0);
                        } else {
                            item.setChecked(1);
                        }

                    } else {
                        // 非抄表巡检项的逻辑 当前是报单非必填的情况
                        if ((item.getMustFillRemark() != 0 && StringUtils.isEmpty(item.getRemark())) ||
                                (item.getMustTakePic() != 0 && item.getPictureUrls().isEmpty())) {
                            //说明 备注或者拍照有必填的
                            item.setChecked(0);
                        } else { // 备注或者拍照没有必填的
                            item.setChecked(1);
                        }
                        item.setAbnormal(1);
                        item.setCheckResult("N1");
                    }
                    startWorkAdapter.notifyItemChanged(position);
                } else {  //此处的逻辑 就是报单必填
                    if (item.getHasMeter() == 1) { //此处是抄表的逻辑
                        recordItem = item;
                        recordPosition = position;
                    } else {  //非抄表巡检项
                        KLog.e("2222");
                        if ((item.getMustFillRemark() != 0 && StringUtils.isEmpty(item.getRemark())) ||
                                (item.getMustTakePic() != 0 && item.getPictureUrls().isEmpty())) {
                            //有必填项 未填
                            item.setChecked(0);
                            // TODO: 2025/2/11 前端说  非抄表的巡检项 如果是异常  那就设置abnormal为1
                            item.setAbnormal(1);
                            item.setCheckResult("N1");
                            KLog.e("2222");
                        } else {
                            //没有必填项了
                            recordItem = item;
                            recordPosition = position;
                            KLog.e("2222");
                            item.setCheckResult("N1");
                        }
                        startWorkAdapter.notifyItemChanged(position);
                    }


                }
                KLog.e(h5Url);
                EventBus.getDefault().post(new BaoTipEvent(h5Url));
                mFlRight.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        Intent intents = new Intent();
                        intents.putExtra(Constant.H5_URL, h5Url);
                        intents.setClass(context, H5Activity.class);
                        Constant.isBao = true;
                        intents.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);  //影响了onActivityResult的回调
                        startActivityForResult(intents, 20001);

                    }
                }, 700);

            }

            @Override
            public void onEntryRequirementClick(String content, String inspectionItemId, boolean isMust) {
                String baseUrl = PreferenceManager.getDefaultSharedPreferences(context).getString(Constant.BASE_ADDRESS_URL, "");
                String nmeSrr = "";
                String locationDesc = "";
                String remake = "";
                String serviceTypeDesc = "";
                try {
                    nmeSrr = URLEncoder.encode((StringUtils.isEmpty(pointsDTO.getAssetDesc()) ? "" : pointsDTO.getAssetDesc()), "UTF-8");
                    locationDesc = URLEncoder.encode((StringUtils.isEmpty(pointsDTO.getLocationDesc()) ? "" : pointsDTO.getLocationDesc()), "UTF-8");
                    remake = URLEncoder.encode("<" + item.getTitle() + ">" + getResources().getString(R.string.Find_an_anomaly) + "。" + content, "UTF-8");
                    serviceTypeDesc = URLEncoder.encode((StringUtils.isEmpty(getDetailsBean.getRecord().getSysServiceTypeDesc()) ? "" : getDetailsBean.getRecord().getSysServiceTypeDesc()), "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    throw new RuntimeException(e);
                }
                String h5Url = baseUrl + "/h5/mytask/" + "?accessToken=" + UserHelper.getToken() + "#/srtask/requiresubmit?requestWay=INSP_REPORT_1&assetId=" + assetId +
                        "&assetName=" + nmeSrr +
                        "&locationId=" + (StringUtils.isEmpty(pointsDTO.getLocationId()) ? "" : pointsDTO.getLocationId()) +
                        "&locationDesc=" + locationDesc +
                        "&projId=" + projId +
                        "&contactPerson=" + (StringUtils.isEmpty(UserHelper.getUserName()) ? "" : UserHelper.getUserName()) +
                        "&reportByTel=" + (StringUtils.isEmpty(UserHelper.getUserPhone()) ? "" : UserHelper.getUserPhone()) +
                        "&reportBy=" + (StringUtils.isEmpty(UserHelper.getUserId()) ? "" : UserHelper.getUserId()) +
                        "&reportByName=" + (StringUtils.isEmpty(UserHelper.getUserName()) ? "" : UserHelper.getUserName()) +
                        "&orgId=" + UserHelper.getUserOwnerOrgId() +
                        "&orderId=" + (StringUtils.isEmpty(pointsDTO.getOrderId()) ? "" : pointsDTO.getOrderId()) +
                        "&pointId=" + pointsDTO.getId() +
                        "&orderChklistId=" + item.getId() +
                        "&taskId=" + presenter.getSharedPrefs().getString("taskId", "") +
                        "&serviceTypeProjId=" + (StringUtils.isEmpty(getDetailsBean.getRecord().getReportServiceTypeId()) ? "" : getDetailsBean.getRecord().getReportServiceTypeId()) +
                        "&serviceTypeDesc=" + serviceTypeDesc +
                        "&type=inspChecklist&descript-text=" + remake +
                        "&backRepair=3&inspDetailID=" + inspectionItemId +
                        "&from=app&imageList=" + new Gson().toJson(item.getPictureUrls());

                item.setRemark(content);
                if (!isMust) {  // isMust 是报单必填 也就是说当前的报工单 里面的内容必须填完 （在没有备注或者拍照必填项的情况下  才能算作是已检） （如果有拍照或者备注的必填项  但是没有填完 也不能算作是已检）
                    if (item.getHasMeter() == 1) {  //抄表的逻辑
                        if ((item.getMustFillRemark() != 0 && StringUtils.isEmpty(item.getRemark())) ||
                                (item.getMustTakePic() != 0 && item.getPictureUrls().isEmpty())) {
                            item.setChecked(0);
                        } else {
                            item.setChecked(1);
                        }
                        item.setAbnormal(1);

                    } else {
                        // 非抄表巡检项的逻辑 当前是报单非必填的情况
                        if ((item.getMustFillRemark() != 0 && StringUtils.isEmpty(item.getRemark())) ||
                                (item.getMustTakePic() != 0 && item.getPictureUrls().isEmpty())) {
                            //说明 备注或者拍照有必填的
                            item.setChecked(0);
                        } else { // 备注或者拍照没有必填的
                            item.setChecked(1);
                        }
                        item.setAbnormal(1);
                        item.setCheckResult("N1");
                    }
                    startWorkAdapter.notifyItemChanged(position);
                } else {  //此处的逻辑 就是报单必填
                    if (item.getHasMeter() == 1) { //此处是抄表的逻辑
                        recordItem = item;
                        recordPosition = position;
                    } else {  //非抄表巡检项

                        if ((item.getMustFillRemark() != 0 && StringUtils.isEmpty(item.getRemark())) ||
                                (item.getMustTakePic() != 0 && item.getPictureUrls().isEmpty())) {
                            //有必填项 未填
                            item.setChecked(0);
                            item.setAbnormal(1);
                            item.setCheckResult("N1");
                        } else {
                            //没有必填项了
                            recordItem = item;
                            recordPosition = position;
                        }
                        startWorkAdapter.notifyItemChanged(position);
                    }
                }

                Intent intents = new Intent();
                EventBus.getDefault().post(new BaoTipEvent(h5Url));
                mFlRight.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        intents.putExtra(Constant.H5_URL, h5Url);
                        intents.setClass(context, H5Activity.class);
                        Constant.isBao = true;
                        intents.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT); //影响了onActivityResult的回调
                        startActivityForResult(intents, 20001);
                    }
                }, 700);

            }
        });
    }

    private void initData() {
        assetId = getIntent().getStringExtra("assetId");
        projId = getIntent().getStringExtra("projId");
        detailId = getIntent().getStringExtra("detailId");
        pointId = getIntent().getStringExtra("pointId");
        KLog.e("9999", pointId);
        databaseManager = new DatabaseManager(context);

        ActivityJsonBean base = databaseManager.getUserByName("CheckDetailsActivity" + detailId);
        if (base != null) {
            if (!TextUtils.isEmpty(base.getJson())) {
                getDetailsBean = GsonUtil.GsonToBean(base.getJson(), GetDetailsBean.class);
            }
        }

        startWorkAdapter.setDetailBean(getDetailsBean);
        if (getDetailsBean == null) return;
        if (!Utils.isEmpty(getDetailsBean.getRecord().getPoints())) {
            for (int i = 0; i < getDetailsBean.getRecord().getPoints().size(); i++) {
                if (pointId.equals(getDetailsBean.getRecord().getPoints().get(i).getId())) {
                    currentPointPosition = i;
                    break;
                }
            }
            KLog.e("updateInfo");
            updateInfo();
        }
    }

    @SuppressLint({"SetTextI18n", "RtlHardcoded"})
    private void updateInfo() {
        // databaseManager.updateUser("CheckDetailsActivity" + detailId, GsonUtil.BeanToJson(getDetailsBean));
        isShowUnChane = true;
        iv_show_un.setSelected(isShowUnChane);
        startWorkAdapter.setShowBoole(isShowUnChane);
        KLog.e("00000" + currentPointPosition);
        pointsDTO = getDetailsBean.getRecord().getPoints().get(currentPointPosition);
        for (int i = 0; i < pointsDTO.getCheckList().size(); i++) {
            KLog.e(pointsDTO.getCheckList().get(i).getHasMeter() + "---" + pointsDTO.getCheckList().get(i).getChecked() + "---" + "---" + pointsDTO.getCheckList().get(i).isHasMasterShow());
        }

        if (!isFromFirst) {
            if (getDetailsBean.getRecord().getPoints().get(currentPointPosition).getMustScan().equals("1")
                    && !CacheHelper.getInstance().getPointScanMarkers(pointsDTO.getId())) {
                KLog.e("2222");
                checkScan(ll_base);
                return;
            }
            if (getDetailsBean.getRecord().getPoints().get(currentPointPosition).getMustScan().equals("2")
                    && !CacheHelper.getInstance().getPointScanMarkers(pointsDTO.getId())) {
                KLog.e("2222");
                checkScan(ll_base);
                return;
            }
        }
        KLog.e(currentPointPosition);
        isFromFirst = false;

        tvTitle.setText(StringUtils.isEmpty(pointsDTO.getAssetDesc()) ? pointsDTO.getLocationDesc() : pointsDTO.getAssetDesc());
        assetId = pointsDTO.getAssetId();

        mTvAllNum.setText(getResources().getString(R.string.How_many_in_total, getDetailsBean.getRecord().getPoints().size()));
        mTvNum.setText(getResources().getString(R.string.How_many_are_there, currentPointPosition + 1));
        if (currentPointPosition + 1 < getDetailsBean.getRecord().getPoints().size()) {
            GetDetailsBean.RecordDTO.PointsDTO nextPoint = getDetailsBean.getRecord().getPoints().get(currentPointPosition + 1);

            if (nextPoint.getLocationDesc().length() > 20) {
                mTvName.setText(nextPoint.getLocationDesc().substring(0, 10) + "..." + nextPoint.getLocationDesc().substring(nextPoint.getLocationDesc().length() - 10, nextPoint.getLocationDesc().length()));
            } else {
                mTvName.setText(nextPoint.getLocationDesc());
            }

        }


        if (currentPointPosition + 1 == 1) { //证明当前是第一个  再往前没有作业了  变换图标
            mFlLeft.setBackgroundResource(R.mipmap.icon_back_cl);
            ivLeft.setImageResource(R.mipmap.icon_left_);
        } else {
            mFlLeft.setBackgroundResource(R.mipmap.icon_background_red);
            ivLeft.setImageResource(R.mipmap.icon_white_back);
        }

        if (currentPointPosition + 1 == getDetailsBean.getRecord().getPoints().size()) { //证明当前是最后一个 后面没有作业 需要显示提交按钮
            llHaveWork.setVisibility(View.GONE);
            llNotHavaWork.setVisibility(View.VISIBLE);
        } else {
            llHaveWork.setVisibility(View.VISIBLE);
            llNotHavaWork.setVisibility(View.GONE);
        }

        if (getDetailsBean.getRecord().getAllowAllNormal() == 1) {
            ll_all_normal.setVisibility(View.VISIBLE);
        } else {
            ll_all_normal.setVisibility(View.GONE);  //不显示全部正常的话 设置只显示未检局左侧
            // ll_show_un.setGravity(Gravity.LEFT);
        }

        if (TextUtils.equals("ASSET", pointsDTO.getType())) {
            mLlHealth.setVisibility(View.VISIBLE);
            if (TextUtils.equals(pointsDTO.getAssetStatus(), "1")) {
                mTvStatus.setText(getResources().getString(R.string.Running));
                mTvStatus.setTextColor(getResources().getColor(R.color.color_32CB6F));
                mTvStop.setText(getResources().getString(R.string.ReportTurn_offMachine));
            } else {
                mTvStop.setText(getResources().getString(R.string.ReportStartMachine));
                mTvStatus.setText(getResources().getString(R.string.InHalt));
                mTvStatus.setTextColor(getResources().getColor(R.color.color_F1484B));
            }
        } else {
            mLlHealth.setVisibility(View.GONE); //如果头部不显示  就让只显示未检变成白色
            ll_show.setBackgroundColor(Color.WHITE);
            LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) ll_show.getLayoutParams();
            // 设置下边距（单位：像素）
            params.bottomMargin = (int) DesUtil.dp2px(10);
            // 设置更新后的 LayoutParams
            ll_show.setLayoutParams(params);
        }
        KLog.e("123---" + pointsDTO.getAssetStatus() + "----" + pointsDTO.getAssetStatus() + "--" + (!StringUtils.isEmpty(pointsDTO.getAssetStatus()) && !pointsDTO.getAssetStatus().equals("1")));
        if (!StringUtils.isEmpty(pointsDTO.getAssetStatus()) && !pointsDTO.getAssetStatus().equals("1")) { // 停机状态 已检异常
            KLog.e("123------");
            KLog.e("123------" + GsonUtil.BeanToJson(pointsDTO.getCheckList()));
            for (GetDetailsBean.RecordDTO.PointsDTO.CheckListDTO checkListDTO : pointsDTO.getCheckList()) {
                KLog.e("123------");
               if (checkListDTO.getHasMeter() == 1) {
//                       checkListDTO.setChecked(1);
//                       checkListDTO.setAbnormal(0);
                       checkListDTO.setHasMasterShow(false);
                       KLog.e("123------");
                }
            }
            pointsDTO.setCheckList(pointsDTO.getCheckList());
        }


        KLog.e(pointsDTO.getId());

        startWorkAdapter.setNewData(pointsDTO.getCheckList());
    }


    private void initListener() {

        mLlJiankang.setOnClickListener(v -> {
            DeviceHealthCardActivity.startActivity(context, assetId, getDetailsBean.getRecord().getProjId());
        });

        llRunCheckCard.setOnClickListener(v -> {
            //https://app.linuxhh.com/ioth5/iot/?accessToken=061a70cc-b056-4a61-b977-b428c28257ca#/asset/monitor?isRInited=1&assetId=1230063802&projId=undefined&fromwhere=mytask_assetDetail
            String baseUrl = PreferenceManager.getDefaultSharedPreferences(context).getString(Constant.BASE_ADDRESS_URL, "");
            String h5Url = baseUrl + "/ioth5/iot/" + "?accessToken=" + UserHelper.getToken() + "#/asset/monitor?isRInited=1&assetId=" + assetId + "&projId=" + projId + "&from=app&fromwhere=mytask_assetDetail";
            goH5Activity(h5Url);
        });

        findViewById(R.id.iv_back).setOnClickListener(v -> {
            if (!FastClickHelperClick.isFastClick()) return;
            updatePoint("back");
        });

        //上一个
        mFlLeft.setOnClickListener(v -> {
            if (FastClickHelperClick.isFastClick()) {
                if (currentPointPosition > 0) {
                    updatePoint("top");
                }
            }
        });

        //下一个
        mFlRight.setOnClickListener(v -> {
            if (FastClickHelperClick.isFastClick()) {
                if (currentPointPosition < getDetailsBean.getRecord().getPoints().size() - 1) {
                    GetDetailsBean.RecordDTO.PointsDTO pointsBean = getDetailsBean.getRecord().getPoints().get(currentPointPosition);
                    List<GetDetailsBean.RecordDTO.PointsDTO.CheckListDTO> checkList = pointsBean.getCheckList();
                    if (getDetailsBean.getRecord().getFixedRoute() == 1) {  //后台设置了按顺序检查
                        for (int i = 0; i < checkList.size(); i++) {
                            if (checkList.get(i).getChecked() != 1) {
                                ToastUtils.showCustomToast(context, R.mipmap.icon_error, getResources().getString(R.string.Current_tasks_must_be_inspected_in_sequence));
                                return;
                            }
                        }
                    }
                    for (int i = 0; i < checkList.size(); i++) {
                        //备注必填  但是没有写备注  还是未检
                        if (checkList.get(i).getMustFillRemark() != 0 && StringUtils.isEmpty(checkList.get(i).getRemark()) && checkList.get(i).getChecked() != 1) {
                            ToastUtils.showCustomToast(context, R.mipmap.icon_error, getResources().getString(R.string.Please_fill_in_the_job_description));
                            return;
                        }
                        //拍照必填  但是没有拍  还是未检
                        if (checkList.get(i).getMustTakePic() != 0 && startWorkAdapter.getData().get(i).getPictureUrls().isEmpty() && checkList.get(i).getChecked() != 1) {
                            ToastUtils.showCustomToast(context, R.mipmap.icon_error, getResources().getString(R.string.No_photo_is_taken_for_the_inspection_item));
                            return;
                        }
                    }
                    isNext = true;
                    updatePoint("next");
                }
                KLog.e(currentPointPosition);
            }
        });

        //mCbView.setOnCheckedChangeListener((buttonView, isChecked) -> startWorkAdapter.setShowBoole(isChecked));
        //只显示未检
        ll_show_un.setOnClickListener(view -> {
            isShowUnChane = !isShowUnChane;
            iv_show_un.setSelected(isShowUnChane);
            startWorkAdapter.setShowBoole(isShowUnChane);
        });

        //全部正常
        ll_all_normal.setOnClickListener(view -> {
            if (!isAllNormal) {
                iv_all_normal.setSelected(true);
                for (int i = 0; i < startWorkAdapter.getData().size(); i++) {
                    GetDetailsBean.RecordDTO.PointsDTO.CheckListDTO checkItem = startWorkAdapter.getData().get(i);
                    if (checkItem.getHasMeter() != 1) { //非水表选项
                        if (checkItem.getMustFillRemark() != 0 || checkItem.getMustTakePic() != 0) { //有必填项
                            if (checkItem.getMustFillRemark() != 0) {
                                //备注必填
                                if (StringUtils.isEmpty(checkItem.getRemark())) {
                                    //但是备注没有填写
                                    checkItem.setCheckResult("Y1");
                                    checkItem.setChecked(0);
                                    startWorkAdapter.notifyItemChanged(i);
                                    continue;
                                } else {
                                    //备注填了 判断图片是不是必填
                                    if (checkItem.getMustTakePic() != 0) {
                                        //拍照是必填
                                        if (checkItem.getPictureUrls().isEmpty()) {
                                            //拍照没填
                                            checkItem.setCheckResult("Y1");
                                            checkItem.setChecked(0);
                                            startWorkAdapter.notifyItemChanged(i);
                                            continue;
                                        } else {
                                            //图片填了
                                            checkItem.setCheckResult("Y1");
                                            checkItem.setChecked(1);
                                            startWorkAdapter.notifyItemChanged(i);
                                            continue;
                                        }

                                    } else {
                                        //图片不是必填
                                        checkItem.setCheckResult("Y1");
                                        checkItem.setChecked(1);
                                        startWorkAdapter.notifyItemChanged(i);
                                        continue;
                                    }
                                }


                            }

                            if (checkItem.getMustTakePic() != 0) {
                                //拍照是必填
                                if (checkItem.getPictureUrls().isEmpty()) {
                                    //拍照没填
                                    checkItem.setCheckResult("Y1");
                                    checkItem.setChecked(0);
                                    startWorkAdapter.notifyItemChanged(i);
                                } else {
                                    //图片填了 检查备注是否是必填
                                    if (checkItem.getMustFillRemark() != 0) {
                                        //备注必填
                                        if (StringUtils.isEmpty(checkItem.getRemark())) {
                                            //但是备注没有填写
                                            checkItem.setCheckResult("Y1");
                                            checkItem.setChecked(0);
                                            startWorkAdapter.notifyItemChanged(i);
                                        } else {
                                            checkItem.setCheckResult("Y1");
                                            checkItem.setChecked(1);
                                            startWorkAdapter.notifyItemChanged(i);
                                        }

                                    } else {
                                        //备注不是必填
                                        checkItem.setCheckResult("Y1");
                                        checkItem.setChecked(1);
                                        startWorkAdapter.notifyItemChanged(i);
                                    }

                                }
                            }

                        } else {
                            checkItem.setCheckResult("Y1");
                            checkItem.setChecked(1);
                            startWorkAdapter.notifyItemChanged(i);
                        }

                    }
                }
                isAllNormal = true;
            }
        });

        //汇报停机
        mTvStop.setOnClickListener(v -> {
            if (TextUtils.equals(pointsDTO.getAssetStatus(), "1")) {//1运行中 2停机
                showBottomPopupWindow(v);
            } else {
                if (NetworkUtils.isAvailable(context)) {
                    presenter.getReportStatus(assetId, "1", projId);
                } else {
                    CacheHelper.getInstance().addOnLineNoGET_REPORT_STATUS(new GETREPORTBean(assetId, "1", projId, getDetailsBean.getRecord().getId(), getDetailsBean.getRecord().getDescription()));
                    getReportStatus("1");
                }
            }
        });

        //提交检查
        tvSubmitCheck.setOnClickListener(v -> {
            if (!FastClickHelperClick.isFastClick()) return;
            updatePoint("submit");

        });
        //返回
        tvBack.setOnClickListener(v -> {
            if (!FastClickHelperClick.isFastClick()) return;
            updatePoint("back");
        });

    }

    private boolean isNext;//是否点击下一步

    private void goH5Activity(String h5Url) {
        // EventBus.getDefault().post(new EventBusWork(h5Url));
        // finish();
        EventBus.getDefault().post(new BaoTipEvent(h5Url));
        mFlRight.postDelayed(new Runnable() {
            @Override
            public void run() {
                Intent intents = new Intent();
                intents.putExtra(Constant.H5_URL, h5Url);
                intents.setClass(context, H5Activity.class);
                Constant.isBao = true;
                intents.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                context.startActivity(intents);
            }
        }, 700);


    }

    boolean isDismiss = true;

    @SuppressLint("SetTextI18n")
    private void checkScan(View view) {
        GetDetailsBean.RecordDTO.PointsDTO pointsBean = getDetailsBean.getRecord().getPoints().get(currentPointPosition);
        if (pointsBean.getMustScan().equals("1") || pointsBean.getMustScan().equals("2")) { //需要扫码
            CenterPopupWindow centerPopupWindow = new CenterPopupWindow(context, R.layout.dialog_center_tip);
            TextView tvContent = centerPopupWindow.getContentView().findViewById(R.id.tv_content);
            centerPopupWindow.getContentView().findViewById(R.id.iv_close).setOnClickListener(v -> {
                centerPopupWindow.dismiss();
            });
            if (pointsBean.getMustScan().equals("1")) {
                tvContent.setText(getResources().getString(R.string.The_inspection_site_must_be_scanned_If_you_cannot_scan_the_code_you_can_choose_to_skip_the_check));
            } else {
                tvContent.setText(getResources().getString(R.string.need_nfc_scan_qr));
            }
            KLog.e("updateInfo" + currentPointPosition);
            centerPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    if (isDismiss) {
                        if (recordType.equals("top")) {
                            currentPointPosition = currentPointPosition + 1;
                        } else if (recordType.equals("next")) {
                            currentPointPosition = currentPointPosition - 1;
                        }
                        KLog.e("updateInfo" + currentPointPosition);
                    }
                    pointsDTO = getDetailsBean.getRecord().getPoints().get(currentPointPosition);
                    KLog.e("22222--" + currentPointPosition);
                }
            });
            TextView tvSkip = centerPopupWindow.getContentView().findViewById(R.id.tv_cancel);
            TextView tvScan = centerPopupWindow.getContentView().findViewById(R.id.tv_sure);
            tvSkip.setText(getResources().getString(R.string.Skip));
            if (pointsBean.getMustScan().equals("1")) {
                tvScan.setText(getResources().getString(R.string.main_scan));
            } else {
                tvScan.setText("NFC" + getResources().getString(R.string.main_scan));
            }
            tvSkip.setOnClickListener(view1 -> {
                isDismiss = false;
                centerPopupWindow.dismiss();
                showSkipReasonPopup(view1);

            });
            tvScan.setOnClickListener(v -> {
                KLog.e("99999----" + currentPointPosition);
                if (pointsBean.getMustScan().equals("1")) {
                    applyPermissionsScan();
                    isDismiss = false;
                    centerPopupWindow.dismiss();
                } else {
                    isDismiss = false;
                    Intent intent = new Intent(context, H5ForNfcActivity.class);
                    intent.putExtra(Constant.SCAN_TO_OPEN_NFC, false);
                    intent.putExtra("from", "start");
                    startActivity(intent);
                    centerPopupWindow.dismiss();
                }

            });
            view.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (!isFinishing() && !isDestroyed()) {
                        if (!centerPopupWindow.isShow()) {
                            centerPopupWindow.show(view);
                        }
                    }
                }
            }, 500);


        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void NfcCodeEvent(NfcCodeEvent str) {
        KLog.e("99999----" + currentPointPosition);
        if (!TextUtils.equals("start", str.getFrom())) return;
        if (str == null || TextUtils.isEmpty(str.getNfcCode())) {
            if (recordType.equals("top")) {
                currentPointPosition = currentPointPosition + 1;
            } else if (recordType.equals("next")) {
                currentPointPosition = currentPointPosition - 1;
            }
            KLog.e("updateInfo");
            updateInfo();
        } else {
            String result = str.getNfcCode();
            if (!TextUtils.isEmpty(result)) {
                //updatePointScan(recordType, result);
                KLog.e("99999----" + currentPointPosition);
                KLog.e("9999", pointId + "----" + result);
                if (!StringUtils.isEmpty(pointsDTO.getAssetId()) && !"0".equals(pointsDTO.getAssetId())) {
                    pointId = pointsDTO.getAssetId();
                } else {
                    pointId = pointsDTO.getLocationId();
                }
                KLog.e("9999", pointId + "----" + result);
                if (pointId.equals(result)) {
                    CacheHelper.getInstance().putPointScanMarkers(pointsDTO.getId());
                    KLog.e("88888");
                    updateInfo();
                } else {
                    KLog.e("88888");
                    ToastUtils.showCustomToast(context, R.mipmap.icon_error, getResources().getString(R.string.Inspection_point_not_matched));
                    if (!StringUtils.isEmpty(recordType)) {
                        if (recordType.equals("top")) {
                            currentPointPosition = currentPointPosition + 1;
                        } else if (recordType.equals("next")) {
                            currentPointPosition = currentPointPosition - 1;
                        }
                        KLog.e("updateInfo");
                        updateInfo();
                    }
                }
            } else {
                if (recordType.equals("top")) {
                    currentPointPosition = currentPointPosition + 1;
                } else if (recordType.equals("next")) {
                    currentPointPosition = currentPointPosition - 1;
                }
                KLog.e("updateInfo");
                updateInfo();
            }
        }

    }


    private void applyPermissionsScan() {
        if (Build.VERSION.SDK_INT >= 23) {
            List<String> permissionLists = new ArrayList<>();
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                permissionLists.add(Manifest.permission.CAMERA);
            }

            if (!permissionLists.isEmpty()) {//说明肯定有拒绝的权限
                ActivityCompat.requestPermissions(this, permissionLists.toArray(new String[0]), 4);
                SnackBarUtil.show(this, "获取相机权限说明：", "用于扫描位置码或者设备码");
            } else {
                Intent intent = new Intent(context, CaptureActivity.class);
                intent.putExtra("bletooth", "1");
                startActivityForResult(intent, 101);
            }

        }

    }

    private View view_bootom_sik;

    private void showSkipReasonPopup(View view) {
        BottomPopupWindow bottomPopupWindow = new BottomPopupWindow(context, R.layout.dialog_skip_reason, true);
        View contentView = bottomPopupWindow.getContentView();
        TextView tvCancel = contentView.findViewById(R.id.tv_cancel);
        view_bootom_sik = contentView.findViewById(R.id.view_bootom);
        TextView tvSure = contentView.findViewById(R.id.tv_sure);
        EditText et_reason = contentView.findViewById(R.id.et_reason);
        TextView tvFontNumber = contentView.findViewById(R.id.tvFontNumber);
        et_reason.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @SuppressLint("SetTextI18n")
            @Override
            public void afterTextChanged(Editable s) {
                tvFontNumber.setText(s.length() + "/" + "100");
                if (s.length() > 100) {
                    s.delete(100, s.length());
                }
            }
        });

        tvCancel.setOnClickListener(v -> {
            bottomPopupWindow.dismiss();
            if (recordType.equals("top")) {
                currentPointPosition = currentPointPosition + 1;
            } else if (recordType.equals("next")) {
                currentPointPosition = currentPointPosition - 1;
            }
        });
        tvSure.setOnClickListener(v -> {
            if (!FastClickHelperClick.isFastClick()) return;
            pointsDTO = getDetailsBean.getRecord().getPoints().get(currentPointPosition);
            if (StringUtils.isEmpty(et_reason.getText().toString())) {
                ToastUtils.showCustomToast(context, R.mipmap.icon_error, context.getResources().getString(R.string.Please_enter_remarks));
                return;
            }
            pointsDTO.setIsSkip(1);
            pointsDTO.setStatus("1");
            updatePoint(recordType);
            bottomPopupWindow.dismiss();
            recordType = "";
        });

        bottomPopupWindow.show(view);
    }

//    private void updatePointScan(String type, String result) {
//        GetDetailsBean.RecordDTO.PointsDTO pointsDTO = null;
//        pointsDTO = getDetailsBean.getRecord().getPoints().get(currentPointPosition);
////        if ("top".equals(type)) {
////            pointsDTO = getDetailsBean.getRecord().getPoints().get(currentPointPosition);
////        } else if ("next".equals(type)) {
////            pointsDTO = getDetailsBean.getRecord().getPoints().get(currentPointPosition);
////        }
//        Log.e("shuchang", "上个或者下一个的assetid----->" + pointsDTO.getAssetId());
//        if (pointsDTO == null) {
//            return;
//        }
//        boolean isRigt = false; //扫描到的是否是目标的扫描点
//        if (!TextUtils.isEmpty(pointsDTO.getAssetId()) && !"0".equals(pointsDTO.getAssetId())) {
//            if (result.equals(pointsDTO.getAssetId())) {
//                isRigt = true;
//            }
//        } else {
//            if (result.equals(pointsDTO.getLocationId())) {
//                isRigt = true;
//            }
//        }
//
//        if (isRigt) {
//            isFirstIn = true;
//            updatePoint(type);
//        } else {
//            switch (recordType) {
//                case "top":
//                    currentPointPosition = currentPointPosition + 1;
//                    break;
//                case "next":
//                    currentPointPosition = currentPointPosition - 1;
//                    break;
//            }
//            ToastUtils.showCustomToast(context, R.mipmap.icon_error, context.getResources().getString(R.string.Inspection_point_not_matched));
//            return;
//        }
//
//    }

    private void updatePoint(String type) {
        KLog.e(currentPointPosition);
        pointsDTO.setCheckList(startWorkAdapter.getData());
        GetDetailsBean.RecordDTO recordDTO = getDetailsBean.getRecord();
        recordDTO.getPoints().set(currentPointPosition, pointsDTO);
        getDetailsBean.setRecord(recordDTO);
        databaseManager.updateUser("CheckDetailsActivity" + detailId, GsonUtil.BeanToJson(getDetailsBean));
        submitCheckList.clear();
        KLog.e(GsonUtil.BeanToJson(pointsDTO.getCheckList()));

        for (GetDetailsBean.RecordDTO.PointsDTO.CheckListDTO checkListDTO : pointsDTO.getCheckList()) {
            KLog.e((checkListDTO.getChecked() == 1) + "--" + (((checkListDTO.getMustFillRemark() != 0 && !StringUtils.isEmpty(checkListDTO.getRemark()))) + "--" + (checkListDTO.getMustTakePic() != 0 && !checkListDTO.getPictureUrls().isEmpty())));
            if (checkListDTO.getChecked() == 1 ||
                    ((checkListDTO.getMustFillRemark() != 0 && !StringUtils.isEmpty(checkListDTO.getRemark()))
                            ||
                            (checkListDTO.getMustTakePic() != 0 && !checkListDTO.getPictureUrls().isEmpty()))) {
                //证明当前有完成的检查项  或者 有必填项 而且人家也填了
                checkListDTO.setHasAttach(!checkListDTO.getPictureUrls().isEmpty() ? 1 : 0);
                checkListDTO.setReadDate(System.currentTimeMillis() + "");
                submitCheckList.add(checkListDTO);
            }

            if (!type.equals("back")) {   //直接点击返回 只保存 不校验
                if (!pointsDTO.getStatus().equals("1") && pointsDTO.getIsSkip() != 1) { //跳过不校验
                    if (checkListDTO.getMustFillRemark() == 1 && checkListDTO.getChecked() != 1) {
                        if (StringUtils.isEmpty(checkListDTO.getRemark())) {
                            ToastUtils.showCustomToast(context, R.mipmap.icon_error, getResources().getString(R.string.Please_fill_in_the_job_description));
                            return;
                        }
                    }

                    if (checkListDTO.getMustTakePic() == 1 && checkListDTO.getChecked() != 1) { //必填并且未检
                        if (null == checkListDTO.getPictureUrls() || checkListDTO.getPictureUrls().isEmpty()) {
                            ToastUtils.showCustomToast(context, R.mipmap.icon_error, getResources().getString(R.string.No_photo_is_taken_for_the_inspection_item));
                            return;
                        }
                    }
                }

            }
        }
        Long actUploadDate = !submitCheckList.isEmpty() ? System.currentTimeMillis() : null;
        String description = getDetailsBean.getRecord().getDescription();
        Long finishDate = !submitCheckList.isEmpty() ? System.currentTimeMillis() : null;
        String id = pointsDTO.getId();
        Integer isSkip = pointsDTO.getIsSkip();
        String locationDesc = pointsDTO.getLocationDesc();
        String offlineDate = DateUtil.getCurrentDate("yyyy/MM/dd HH:mm:ss");
        String orderId = pointsDTO.getOrderId();

        String status = "";
        if (submitCheckList.size() == startWorkAdapter.getData().size()) {
            status = "3";
            isSkip = 0;
        } else if (!submitCheckList.isEmpty() && submitCheckList.size() < startWorkAdapter.getData().size()) {
            status = "2";
            isSkip = 0;
        } else if (submitCheckList.isEmpty()) {
            status = "1";
        }

        getDetailsBean.getRecord().getPoints().get(currentPointPosition).setCheckList(startWorkAdapter.getData());
        if (NetworkUtils.isAvailable(context)) {
            KLog.e("00000" + currentPointPosition);
            presenter.updateInspectionPoint(projId, actUploadDate, submitCheckList, description, finishDate, id, isSkip, locationDesc, offlineDate, orderId, status, type, workOrderId);
        } else {
            //提交表单的离线
            HashMap<String, Object> map = new HashMap<>();
            map.put("actUploadDate", actUploadDate);
            map.put("checkList", submitCheckList);
            map.put("description", description);
            map.put("finishDate", finishDate);
            map.put("id", id);
            map.put("isSkip", isSkip);
            map.put("locationDesc", locationDesc);
            map.put("offlineDate", offlineDate);
            map.put("orderId", orderId);
            map.put("status", status);
            map.put("projId", projId);
            if (!StringUtils.isEmpty(workOrderId)) {
                map.put("workOrderId", workOrderId);
            }
            String json = new Gson().toJson(map);
            //databaseManager.insertInspectPoint(json);
            CacheHelper.getInstance().addSubmitPoint(id, projId, description, json, getDetailsBean.getRecord().getId());
            if (isNext) {
                suoDateList.add(new UpDateStatusEvent(id, projId, status));
                if (TextUtils.equals("submit", type) || TextUtils.equals("back", type)) {
                    EventBus.getDefault().post(new UpdataPoint(suoDateList));
                    KLog.e(GsonUtil.BeanToJson(suoDateList));
                }
            } else {
                EventBus.getDefault().post(new UpDateStatusEvent(id, projId, status));
                KLog.e(GsonUtil.BeanToJson(status));
            }
            updatePointSuccess(type);


        }

    }

    List<UpDateStatusEvent> suoDateList = new ArrayList<>();

    @Override
    protected StartWorkPersenter createPresenter() {
        return new StartWorkPersenter();
    }


    private List<String> selectFileList = new ArrayList<>();

    private void uploadImageFile(ArrayList<String> images) {
        for (int i = 0; i > images.size(); i++) {
            presenter.uploadImageNew(new File(images.get(i)));
        }
    }


    @Override
    public void getRunListPager(RunListPagerBean bean) {
        new DatabaseManager(context).upsertJson(getClass().getSimpleName(), GsonUtil.BeanToJson(bean));
        List<RunListPagerBean.RecordsDTO> records = bean.getRecords();
        if (null != records && !records.isEmpty()) {
            for (int i = 0; i < records.size(); i++) {
                if (records.get(i).getIsComp() == 0) {  //有异常
                    ll_device_health_card_error.setVisibility(View.VISIBLE);
                    // 创建Alpha动画：从不透明到透明，再到不透明
                    AlphaAnimation alphaAnimation = new AlphaAnimation(1.0f, 0.0f);
                    alphaAnimation.setDuration(500);  // 动画持续时间500毫秒
                    alphaAnimation.setRepeatMode(Animation.REVERSE);  // 动画反转
                    alphaAnimation.setRepeatCount(Animation.INFINITE);  // 无限次循环
                    // 启动动画
                    tv_have_error.startAnimation(alphaAnimation);
                    break;
                }
            }
            if (!NetworkUtils.isAvailable(context)) {
                ll_zai.setVisibility(View.GONE);
                ll_lixian.setVisibility(View.VISIBLE);
            }
        }

    }

    @Override
    public void getReportStatus(String type) {
        pointsDTO.setAssetStatus(type);
        if (TextUtils.equals(type, "1")) {
            mTvStatus.setText(getResources().getString(R.string.Running));
            mTvStatus.setTextColor(getResources().getColor(R.color.color_32CB6F));
            mTvStop.setText(getResources().getString(R.string.ReportTurn_offMachine));

            if (!StringUtils.isEmpty(pointsDTO.getAssetStatus()) && pointsDTO.getAssetStatus().equals("1")) { //开机的话  抄表显示出来
                if (isClickShutDown) {  //点过停机
                    for (GetDetailsBean.RecordDTO.PointsDTO.CheckListDTO checkListDTO : pointsDTO.getCheckList()) {
                        if (checkListDTO.getHasMeter() == 1) {
                            checkListDTO.setHasMasterShow(true);
                        }
                    }
                } else {
                    for (GetDetailsBean.RecordDTO.PointsDTO.CheckListDTO checkListDTO : pointsDTO.getCheckList()) {
                        if (checkListDTO.getHasMeter() == 1) {
                            checkListDTO.setHasMasterShow(true);
                            checkListDTO.setChecked(1);
                            checkListDTO.setAbnormal(0);
                        }
                    }
                }

                pointsDTO.setCheckList(pointsDTO.getCheckList());
            }
        } else {
            isClickShutDown = true;
            mTvStatus.setText(getResources().getString(R.string.InHalt));
            mTvStatus.setTextColor(getResources().getColor(R.color.color_F1484B));
            mTvStop.setText(getResources().getString(R.string.ReportStartMachine));

            if (!StringUtils.isEmpty(pointsDTO.getAssetStatus()) && !pointsDTO.getAssetStatus().equals("1")) { //停机状态下  抄表都设置为已检异常
                for (GetDetailsBean.RecordDTO.PointsDTO.CheckListDTO checkListDTO : pointsDTO.getCheckList()) {
                    if (checkListDTO.getHasMeter() == 1) {
                        checkListDTO.setChecked(1);
                        checkListDTO.setAbnormal(0);
                        checkListDTO.setHasMasterShow(false);
                        KLog.e("123-----");
                    }
                }
                pointsDTO.setCheckList(pointsDTO.getCheckList());
            }
        }
        getDetailsBean.getRecord().getPoints().set(currentPointPosition, pointsDTO);
        KLog.e("updateInfo");
        updateInfo();
    }

    @Override
    public void uploadSuccess(String imgUrl) {
        KLog.e("2222");
        ToastUtils.showCustomToast(context, R.mipmap.icon_success, getResources().getString(R.string.Upload_successfully));
    }


    private void showBottomPopupWindow(View anchor) {
        if (bottomPopupWindow == null) {
            bottomPopupWindow = new BottomPopupWindow(context, R.layout.dialog_stop_select);
            View view = bottomPopupWindow.getContentView();
            RecyclerView rvShutDown = view.findViewById(R.id.rv_shut_down);
            rvShutDown.setLayoutManager(new LinearLayoutManager(context));
            ShutDownAdapter shutDownAdapter = new ShutDownAdapter(R.layout.item_shut_down);
            rvShutDown.setAdapter(shutDownAdapter);
            if (!FMCApplication.shutDownList.isEmpty()) {
                shutDownAdapter.setNewData(FMCApplication.shutDownList);
            } else {
                String json = CacheHelper.getInstance().getMapJson("ReportList");
                if (!TextUtils.isEmpty(json)) {
                    FMCApplication.shutDownList.clear();
                    FMCApplication.shutDownList.addAll(GsonUtil.jsonToList(json, OperateReportBean.RecordBean.class));
                    shutDownAdapter.setNewData(FMCApplication.shutDownList);
                }
            }
            shutDownAdapter.setOnItemClickListener((adapter, view1, position) -> {
                OperateReportBean.RecordBean item = shutDownAdapter.getItem(position);
                presenter.getReportStatus(assetId, item.getValue(), projId);
                bottomPopupWindow.dismiss();
                CacheHelper.getInstance().addOnLineNoGET_REPORT_STATUS(new GETREPORTBean(assetId, "4", projId, getDetailsBean.getRecord().getId(), getDetailsBean.getRecord().getDescription()));
                getReportStatus(item.getValue());
            });


//            view.findViewById(R.id.tv_1).setOnClickListener(v -> {
//                presenter.getReportStatus(assetId, "3", projId);
//                bottomPopupWindow.dismiss();
//            });
//            view.findViewById(R.id.tv_2).setOnClickListener(v -> {
//                presenter.getReportStatus(assetId, "4", projId);
//                bottomPopupWindow.dismiss();
//            });
            view.findViewById(R.id.tv_cancel).setOnClickListener(v -> {
                bottomPopupWindow.dismiss();
            });

        }
        bottomPopupWindow.show(anchor);
    }


    private void showCenterPopupWindow(View anchor, int position, List<ImageSelectBean> list) {
        ImageSelectBean selectBean = list.get(position);
        recordList.clear();
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getImg().contains("mp4") || list.get(i).getImg().contains("MP4") || TextUtils.isEmpty(list.get(i).getImg())) {
                continue;
            }
            recordList.add(list.get(i));
        }
        CenterPopupWindow centerPopupWindow = new CenterPopupWindow(context, R.layout.dialog_center_img);
        ViewPager viewPager = centerPopupWindow.getContentView().findViewById(R.id.viewPager);
        ImageView iv_left = centerPopupWindow.getContentView().findViewById(R.id.iv_left);
        ImageView iv_right = centerPopupWindow.getContentView().findViewById(R.id.iv_right);
        iv_left.setOnClickListener(v -> {
            int currentItem = viewPager.getCurrentItem();
            if (currentItem > 0) {
                viewPager.setCurrentItem(currentItem - 1, true); // true for smooth scroll
            }
        });
        iv_right.setOnClickListener(v -> {
            int currentItem = viewPager.getCurrentItem();
            int totalItems = viewPager.getAdapter().getCount();
            if (currentItem < totalItems - 1) {
                viewPager.setCurrentItem(currentItem + 1, true); // true for smooth scroll
            }
        });


        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {

            }

            @Override
            public void onPageSelected(int i) {
                if (recordList.size() == 1) {
                    iv_left.setVisibility(View.GONE);
                    iv_right.setVisibility(View.GONE);
                } else {
                    if (i <= 0) {
                        iv_left.setVisibility(View.GONE);
                        iv_right.setVisibility(View.VISIBLE);
                    } else if (i >= recordList.size() - 1) {
                        iv_left.setVisibility(View.VISIBLE);
                        iv_right.setVisibility(View.GONE);
                    } else {
                        iv_left.setVisibility(View.VISIBLE);
                        iv_right.setVisibility(View.VISIBLE);
                    }
                }
            }


            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });
        centerPopupWindow.getContentView().findViewById(R.id.iv_close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                centerPopupWindow.dismiss();
            }
        });

//        recordList.clear();
//        if (StringUtils.isEmpty(list.get(0).getImg())) {
//            recordList.addAll(list);
//            recordList.remove(0);
//        } else {
//            recordList.addAll(list);
//        }
        ImagePagerAdapter pagerAdapter = new ImagePagerAdapter(context, recordList);
        viewPager.setAdapter(pagerAdapter);
        int positionSelect = 0;
        for (int i = 0; i < recordList.size(); i++) {
            if (TextUtils.equals(selectBean.getImg(), recordList.get(i).getImg())) {
                positionSelect = i;
            }
        }
        if (positionSelect == 1) {
            iv_left.setVisibility(View.GONE);
            iv_right.setVisibility(View.VISIBLE);
        }
        if (recordList.size() == 1) {
            iv_left.setVisibility(View.GONE);
            iv_right.setVisibility(View.GONE);
        } else {
            if (positionSelect == 0) {
                iv_left.setVisibility(View.GONE);
                iv_right.setVisibility(View.VISIBLE);
            } else if (positionSelect == recordList.size() - 1) {
                iv_left.setVisibility(View.VISIBLE);
                iv_right.setVisibility(View.GONE);
            } else {
                iv_left.setVisibility(View.VISIBLE);
                iv_right.setVisibility(View.VISIBLE);
            }
        }
        viewPager.setCurrentItem(positionSelect);
        centerPopupWindow.show(anchor);
    }


    /**
     * 照片提示框
     */
    List<String> permissionLists10 = new ArrayList<>();
    List<String> permissionLists11 = new ArrayList<>();
    List<String> permissionLists12 = new ArrayList<>();
    List<String> permissionLists13 = new ArrayList<>();

    private void showCreamOrRecordVideoDialog() {
        final CreamOrVideoRecordDialog dialog = new CreamOrVideoRecordDialog(this);
        dialog.show();
        dialog.setClickListener(new CreamOrVideoRecordDialog.ClickListenerInterface() {
            @Override
            public void takePhoto() {//拍照
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    //动态申请权限
                    applyPermissions(true, () -> nativeTakePhoto());
                } else {
                    nativeTakePhoto();
                }
                dialog.dismiss();
            }

            @Override
            public void recordVideo() {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    applyPermissions(false, () -> {
                        Intent intent = new Intent();
                        videoId = System.currentTimeMillis() + "" + (int) ((Math.random() * 9 + 1) * 100000);
                        intent.setClass(context, RecordVideoActivity.class);
                        startActivityForResult(intent, RECORDVIDEO);
                    });
                } else {
                    Intent intent = new Intent();
                    videoId = System.currentTimeMillis() + "" + (int) ((Math.random() * 9 + 1) * 100000);
                    intent.setClass(context, RecordVideoActivity.class);
                    startActivityForResult(intent, RECORDVIDEO);
                }
                dialog.dismiss();

            }
        });
    }

    private static final int OPEN_ABLUM = 24;

    private void applyPermissions(boolean isCamera, RequestPermissionsListener listener) {

        if (Build.VERSION.SDK_INT >= 23) {
            permissionLists10.clear();
            permissionLists11.clear();
            permissionLists12.clear();
            permissionLists13.clear();
            //1.拍摄照片和录制内容
            //2。访问您设备上的照片。媒体文件内容和文件
            //3。录制视频
            //
            if (isCamera) {
                if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                    permissionLists10.add(Manifest.permission.CAMERA);
                }

                if (ContextCompat.checkSelfPermission(StartWorkActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    permissionLists12.add(Manifest.permission.ACCESS_FINE_LOCATION);
                }
                if (ContextCompat.checkSelfPermission(StartWorkActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    permissionLists12.add(Manifest.permission.ACCESS_COARSE_LOCATION);
                }

                if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    permissionLists13.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
                }


                if (!permissionLists10.isEmpty()) {
                    ActivityCompat.requestPermissions(this, permissionLists10.toArray(new String[permissionLists10.size()]), 10);
                    snackbar = SnackBarUtil.show(this, "获取拍摄照片和录制内容的权限说明：", "用于拍照和录制视频");
                } else if (!permissionLists13.isEmpty()) {//说明肯定有拒绝的权限
                    ActivityCompat.requestPermissions(this, permissionLists13.toArray(new String[permissionLists13.size()]), 13);
                    snackbar = SnackBarUtil.show(this, "获取您设备上的照片.媒体文件内容和文件的权限说明：", "用于储存照片和视频");
                } else if (!permissionLists12.isEmpty()) {
                    ActivityCompat.requestPermissions(this, permissionLists12.toArray(new String[permissionLists12.size()]), 12);
                    snackbar = SnackBarUtil.show(this, "获取您地理位置的权限说明：", "用于记录当前的位置");
                } else {
                    if (snackbar != null) {
                        snackbar.dismiss();
                    }
                    listener.requestSuccessCallback();
                }
                if (snackbar != null & mRvStart != null) {
                    mRvStart.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            snackbar.dismiss();
                        }
                    }, 3000);
                }
            } else {

                if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
                    permissionLists11.add(Manifest.permission.RECORD_AUDIO);
                }

                if (ContextCompat.checkSelfPermission(StartWorkActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    permissionLists12.add(Manifest.permission.ACCESS_FINE_LOCATION);
                }
                if (ContextCompat.checkSelfPermission(StartWorkActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    permissionLists12.add(Manifest.permission.ACCESS_COARSE_LOCATION);
                }

                if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    permissionLists13.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
                }

                if (!permissionLists11.isEmpty()) {
                    ActivityCompat.requestPermissions(this, permissionLists11.toArray(new String[permissionLists11.size()]), 11);
                    snackbar = SnackBarUtil.show(this, "获取麦克风和录制的权限说明：", "用于录制视频");
                } else if (!permissionLists13.isEmpty()) {//说明肯定有拒绝的权限
                    ActivityCompat.requestPermissions(this, permissionLists13.toArray(new String[permissionLists13.size()]), 13);
                    snackbar = SnackBarUtil.show(this, "获取您设备上的照片.媒体文件内容和文件的权限说明：", "用于储存照片和视频");
                } else if (!permissionLists12.isEmpty()) {
                    ActivityCompat.requestPermissions(this, permissionLists12.toArray(new String[permissionLists12.size()]), 12);
                    snackbar = SnackBarUtil.show(this, "获取您地理位置的权限说明：", "用于记录当前的位置");
                } else {
                    if (snackbar != null) {
                        snackbar.dismiss();
                    }
                    listener.requestSuccessCallback();
                }
                if (snackbar != null & mRvStart != null) {
                    mRvStart.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            snackbar.dismiss();
                        }
                    }, 3000);
                }
            }

        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[],
                                           int[] grantResults) {
        if (snackbar != null) {
            snackbar.dismiss();
        }
    }

    private String imageName = "";
    private Snackbar snackbar;
    public static final int TAKEPIC_H5 = 14;

    /**
     * 拍照
     */
    public void nativeTakePhoto() {
        imageName = ImageUtils.getImageName(this) + ".jpg";
        if (Build.BRAND.equalsIgnoreCase("nokia")) {
            Utility.startPhotoActivityForH5(StartWorkActivity.this, TAKEPIC_H5, ImageUtils.getH5ImagePath(imageName, context));
        } else {
            Intent intent = new Intent(this, CameraOneActivity.class);
            intent.putExtra("imagename", imageName);
            startActivityForResult(intent, TAKEPIC_H5);
            overridePendingTransition(0, 0);
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 101) {//扫码后
            if (data != null) {
                Bundle bundle = data.getExtras();
                if (null != bundle) {
                    String result = bundle.getString(CaptureActivity.SCAN_RESULT);
                    if (null != result) {
                        //updatePointScan(recordType, result);
                        if (!StringUtils.isEmpty(pointsDTO.getAssetId()) && !"0".equals(pointsDTO.getAssetId())) {
                            pointId = pointsDTO.getAssetId();
                        } else {
                            pointId = pointsDTO.getLocationId();
                        }

                        if (pointId.equals(result)) {
                            CacheHelper.getInstance().putPointScanMarkers(pointsDTO.getId());
                            KLog.e("updateInfo");
                            updateInfo();
                        } else {
                            ToastUtils.showCustomToast(context, R.mipmap.icon_error, getResources().getString(R.string.Inspection_point_not_matched));
                            if (!StringUtils.isEmpty(recordType)) {
                                if (recordType.equals("top")) {
                                    currentPointPosition = currentPointPosition + 1;
                                } else if (recordType.equals("next")) {
                                    currentPointPosition = currentPointPosition - 1;
                                }
                                KLog.e("updateInfo");
                                updateInfo();
                            }
                        }
                    } else {
                        KLog.e("3333");
                    }
                } else {
                    KLog.e("3333");
                }

            } else {
                if (recordType.equals("top")) {
                    currentPointPosition = currentPointPosition + 1;
                } else if (recordType.equals("next")) {
                    currentPointPosition = currentPointPosition - 1;
                }
                KLog.e("updateInfo");
                updateInfo();
            }
        } else if (requestCode == TAKEPIC_H5) {
            //打开图片编辑页面
            //h5拍照,拍照成功返回结果是-1
            if (resultCode == -1) {
                Intent intent = new Intent(this, ImageEditActivity.class);
                intent.putExtra("imageName", imageName);
                intent.putExtra("locationDescribe", H5Activity.locationDescribe);
                intent.putExtra("intentType", 0);
                startActivityForResult(intent, IMAGEEDIT_OK);
            }

        } else if (requestCode == IMAGEEDIT_OK) {
            if (resultCode == Constant.EDITIMAGE_OK) {
                String pathUri = data.getStringExtra("pathuri");
                String path = data.getStringExtra("path");
                imageName = imageName.replace(".jpg", ".jpeg");

                if (NetworkUtils.isAvailable(context)) {
                    //上传图片
                    presenter.uploadImgForClient(path, path, imageName.split("\\.")[0]);
                } else {
                    GetDetailsBean.RecordDTO.PointsDTO pointsDTO1 = getDetailsBean.getRecord().getPoints().get(currentPointPosition);
                    String pointPosition = pointsDTO1.getId();
                    CacheHelper.getInstance().saveUploadPoint(pointPosition);
                    String pointCheckId = pointsDTO.getCheckList().get(selectPosition).getId();
                    KLog.e("222222----" + selectPosition + "---" + currentPointPosition);
                    new ImageCompressor(context).compressImageInPlace(path, new OnCompressListener() {
                        @Override
                        public void onStart() {

                        }

                        @Override
                        public void onSuccess(File file) {
                            String listId = getDetailsBean.getRecord().getId();
                            CacheHelper.getInstance().addUploadImage(listId, pointsDTO.getId(), new ImageUploadBean(file.getPath(), file.getPath(), imageName.split("\\.")[0], pointsDTO1.getAssetDesc(), pointPosition, pointCheckId), getDetailsBean.getRecord().getDescription());
                            hideLoading();
                        }

                        @Override
                        public void onError(Throwable e) {

                        }
                    });
                    //存储
                    onErrorUploadMethod(path, path, imageName.split("\\.")[0], "", false);
                }
            } else {
                //用户点了回退，删除刚拍照过的图片
                FileUtil.deleteOneFile(ImageUtils.getH5ImagePath(imageName, this));
            }
        } else if (requestCode == OPEN_ABLUM) {
            if (data == null) {
                return;
            }
            imageName = ImageUtils.getImageName(this) + ".jpg";
            Uri selectedImage = data.getData(); //获取系统返回的照片的Uri
            if (selectedImage == null) {
                return;
            }
            BitmapUtils.saveJPGE_After(context, BitmapUtils.uriToBitmap(this, selectedImage),
                    imageName, 100);
            Intent intent = new Intent(this, ImageEditActivity.class);
            intent.putExtra("imageName", imageName);
            intent.putExtra("locationDescribe", H5Activity.locationDescribe);
            intent.putExtra("intentType", 1);
            startActivityForResult(intent, IMAGEEDIT_OK);
        } else if (requestCode == RECORDVIDEO) {
            if (data != null) {
                //录制视频返回的url
                String url = data.getStringExtra(Constant.RECORD_VIDEO_OK);
//                takePhotoEditVideoOkCallBack(videoId);
                uploadVideo(url, videoId);
            }
        } else if (requestCode == WATER_MATER_SETTING) {
            if (resultCode == RESULT_OK) {
                if (null == data) {
                    return;
                }

                String item = data.getStringExtra("item");
                GetDetailsBean.RecordDTO.PointsDTO.CheckListDTO itemValue = GsonUtil.GsonToBean(item, GetDetailsBean.RecordDTO.PointsDTO.CheckListDTO.class);
                int position = data.getIntExtra("position", 0);
                KLog.e("WATER_MATER_SETTING" + item);
                GetDetailsBean.RecordDTO.PointsDTO.CheckListDTO adapterItem = startWorkAdapter.getItem(position);
                adapterItem.setAbnormal(itemValue.getAbnormal());
                adapterItem.setRemark(itemValue.getRemark());
                adapterItem.setChecked(itemValue.getChecked());
                adapterItem.setMeterRead(itemValue.getMeterRead());
                adapterItem.setPictureUrls(itemValue.getPictureUrls());
                adapterItem.setWorkOrderId(itemValue.getWorkOrderId());
                startWorkAdapter.notifyItemChanged(position);
            }
        } else if (requestCode == 20001) {
            if (resultCode == RESULT_OK) {
                KLog.e("2222");
                String json = data.getStringExtra("json");
                if (!StringUtils.isEmpty(json)) {
                    try {
                        JSONObject jsonObject = new JSONObject(json);
                        if (jsonObject.has("checkId")) {
                            String checkId = jsonObject.getString("checkId");
                            if (jsonObject.has("orderId")) {
                                String orderId = jsonObject.getString("orderId");
                                workOrderId = orderId;
                                Log.e("longlonglong", workOrderId);
                                for (int i = 0; i < startWorkAdapter.getData().size(); i++) {
                                    if (startWorkAdapter.getData().get(i).getId().equals(checkId)) {
                                        startWorkAdapter.getData().get(i).setWorkOrderId(orderId);
                                        break;
                                    }
                                }

                            }
                        }


                    } catch (JSONException e) {
                        throw new RuntimeException(e);
                    }
                }

                if (null != recordItem && recordPosition != -1) {
                    if (recordItem.getHasMeter() == 1) {
                        recordItem.setAbnormal(1);
                    } else {
                        recordItem.setAbnormal(1);
                        recordItem.setCheckResult("N1");
                    }

                    if ((recordItem.getMustFillRemark() != 0 && StringUtils.isEmpty(recordItem.getRemark())) ||
                            (recordItem.getMustTakePic() != 0 && recordItem.getPictureUrls().isEmpty())) {
                        recordItem.setChecked(0);
                    } else {
                        recordItem.setChecked(1);
                    }
                    startWorkAdapter.notifyItemChanged(recordPosition);

                    recordItem = null;
                    recordPosition = -1;
                }

            }


        }

    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (!FastClickHelperClick.isFastClick()) return true;
        pointsDTO.setCheckList(startWorkAdapter.getData());
        GetDetailsBean.RecordDTO recordDTO = getDetailsBean.getRecord();
        recordDTO.getPoints().set(currentPointPosition, pointsDTO);
        getDetailsBean.setRecord(recordDTO);
        databaseManager.updateUser("CheckDetailsActivity" + detailId, GsonUtil.BeanToJson(getDetailsBean));
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            updatePoint("back");
            EventBus.getDefault().post(new UpdataPoint(suoDateList));
            if (Constant.isBao) {
                Intent intent = new Intent(context, CheckDetailsActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                context.startActivity(intent);
                KLog.e(Constant.isBao);
                finish();
            } else {
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    private void onFinish() {
        if (pointsDTO == null || startWorkAdapter == null || getDetailsBean == null) {
            finish();
        }
        pointsDTO.setCheckList(startWorkAdapter.getData());
        GetDetailsBean.RecordDTO recordDTO = getDetailsBean.getRecord();
        recordDTO.getPoints().set(currentPointPosition, pointsDTO);
        getDetailsBean.setRecord(recordDTO);
        //   databaseManager.updateUser("CheckDetailsActivity" + detailId,GsonUtil.BeanToJson(getDetailsBean));

        if (!isFinishing() && !isDestroyed()) {
            if (Constant.isBao) {
                Intent intent = new Intent(context, CheckDetailsActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                context.startActivity(intent);
                KLog.e(Constant.isBao);
                finish();
                KLog.e("22222");
            } else {
                finish();
            }
        }

    }

    //UploadImage baseData, String photoLocationUrl
    @Override
    public void uploadImgForClientSuccess(UploadImage baseData, String locationUrl) {
        if (null != baseData) {
            List<UploadImage.RecordBean> record = baseData.getRecord();
            if (null != record && !record.isEmpty()) {
                UploadImage.RecordBean recordBean = record.get(0);
                if (null != recordBean) {
                    String url = recordBean.getUrl();
                    String markersUrl = recordBean.getThumburl();
                    String picId = recordBean.getId();
                    presenter.updateInspectionPointWorkRequest(picId, url, url, pointsDTO.getCheckList().get(selectPosition).getId(), locationUrl, pointsDTO.getCheckList().get(selectPosition).getTitle(), true);
                }
            }
        }

    }

    @Override
    public void uploadVideoSuccess(String url, String localUrl, String id) {
        presenter.updateInspectionPointWorkRequest(id, url, url, pointsDTO.getCheckList().get(selectPosition).getId(), localUrl, pointsDTO.getCheckList().get(selectPosition).getTitle(), false);

    }


    //String url, String ids
    @Override
    public void uploadImgForClientOnError(String uploadUrl, String locationUrl, String id) {
        onErrorUploadMethod(uploadUrl, locationUrl, id, "", false);
    }

    @Override
    public void updateInspectionPointWorkRequestSuccess(String picId, String url, String shrinkUrl, boolean isPic) {
        ToastUtils.showCustomToast(context, R.mipmap.icon_success, getString(R.string.Upload_successfully));
        if (isPic) {
            GetDetailsBean.RecordDTO.PointsDTO.CheckListDTO.PictureUrlsDTO pictureUrlsDTO = new GetDetailsBean.RecordDTO.PointsDTO.CheckListDTO.PictureUrlsDTO();
            pictureUrlsDTO.setUrl(url);
            pictureUrlsDTO.setThumburl(shrinkUrl);
            pictureUrlsDTO.setId(picId);
            KLog.e("2222----" + selectPosition + "----" + currentPointPosition);
            startWorkAdapter.getItem(selectPosition).getPictureUrls().add(pictureUrlsDTO);
            String picUrl = presenter.getSharedPrefs().getString(Constant.BASE_ADDRESS_URL, "") + url;
            startWorkAdapter.addImageList(picUrl, selectPosition);
            //isShowEmpty(selectPosition);
            FileUtil.deleteOneFile(ImageUtils.getH5ImagePath(picId + ".jpeg", this));

            GetDetailsBean.RecordDTO.PointsDTO.CheckListDTO adapterItem = startWorkAdapter.getItem(selectPosition);
            if (adapterItem.getMustFillRemark() != 0) {
                if (StringUtils.isEmpty(adapterItem.getRemark())) {
                    //备注必填 但是没填
                    return;
                }
            }

            if (adapterItem.getMustTakePic() != 0) {
                if (adapterItem.getPictureUrls().isEmpty()) {
                    //拍照必填 但是没填
                    return;
                }
            }

            if (!StringUtils.isEmpty(adapterItem.getCheckResult())) {  //证明当前已经选择了正常 或者异常
                adapterItem.setChecked(1);
            }
            startWorkAdapter.notifyItemChanged(selectPosition);
            EventBus.getDefault().post(new UploadEventLoad());
        } else {
            //        //这里在适配器里更新
            ToastMessage(getResources().getString(R.string.upload_success));

            GetDetailsBean.RecordDTO.PointsDTO.CheckListDTO.PictureUrlsDTO pictureUrlsDTO = new GetDetailsBean.RecordDTO.PointsDTO.CheckListDTO.PictureUrlsDTO();
            pictureUrlsDTO.setUrl(url);
            pictureUrlsDTO.setThumburl(url);
            pictureUrlsDTO.setId(picId);

            startWorkAdapter.getItem(selectPosition).getPictureUrls().add(pictureUrlsDTO);
            String picUrl = presenter.getSharedPrefs().getString(Constant.BASE_ADDRESS_URL, "") + url;
            startWorkAdapter.addVideoList(picUrl, selectPosition);
            //isShowEmpty(selectPosition);


            GetDetailsBean.RecordDTO.PointsDTO.CheckListDTO adapterItem = startWorkAdapter.getItem(selectPosition);
            if (adapterItem.getMustFillRemark() != 0) {
                if (StringUtils.isEmpty(adapterItem.getRemark())) {
                    //备注必填 但是没填
                    return;
                }
            }

            if (adapterItem.getMustTakePic() != 0) {
                if (adapterItem.getPictureUrls().isEmpty()) {
                    //拍照必填 但是没填
                    return;
                }
            }

            if (!StringUtils.isEmpty(adapterItem.getCheckResult())) {  //证明当前已经选择了正常 或者异常
                adapterItem.setChecked(1);
            }
            startWorkAdapter.notifyItemChanged(selectPosition);
        }

    }

    @Override
    public void updateInspectionPointWorkRequestFail(String picId, String url, String shrinkUrl, String locationUrl, boolean isPic) {
        if (isPic) {
            onErrorUploadMethod(url, locationUrl, picId, shrinkUrl, true);
        } else {
            hideLoading();
            GetDetailsBean.RecordDTO.PointsDTO.CheckListDTO.PictureUrlsDTO pictureUrlsDTO = new GetDetailsBean.RecordDTO.PointsDTO.CheckListDTO.PictureUrlsDTO();
            pictureUrlsDTO.setUrl(url);
            pictureUrlsDTO.setId(picId);
            pictureUrlsDTO.setThumburl(url);
            List<GetDetailsBean.RecordDTO.PointsDTO.CheckListDTO.PictureUrlsDTO> list = pointsDTO.getCheckList().get(selectPosition).getPictureUrls();
            if (null != list) {
                list.add(pictureUrlsDTO);
            }
            pointsDTO.getCheckList().get(selectPosition).setPictureUrls(list);
            startWorkAdapter.addVideoList(url, selectPosition);
            //isShowEmpty(selectPosition);
            startWorkAdapter.notifyItemChanged(selectPosition);
            //存到数据库
            Map<String, Object> map = new HashMap<>();
            map.put("ids", picId);
            map.put("url", url);
            String pointPosition = getDetailsBean.getRecord().getPoints().get(currentPointPosition).getId();
            map.put("point", pointPosition);
            map.put("des", getDetailsBean.getRecord().getPoints().get(currentPointPosition).getAssetDesc());
            String json = new Gson().toJson(map);
            databaseManager.insertInspectPic(json);
        }

    }

    private void onErrorUploadMethod(String uploadUrl, String locationUrl, String id, String shrinkUrl, boolean isHaveShrinkUrl) {
        GetDetailsBean.RecordDTO.PointsDTO.CheckListDTO.PictureUrlsDTO pictureUrlsDTO = new GetDetailsBean.RecordDTO.PointsDTO.CheckListDTO.PictureUrlsDTO();
        pictureUrlsDTO.setUrl(uploadUrl);
        pictureUrlsDTO.setId(id);
        pictureUrlsDTO.setThumburl(isHaveShrinkUrl ? shrinkUrl : uploadUrl);
        List<GetDetailsBean.RecordDTO.PointsDTO.CheckListDTO.PictureUrlsDTO> list = pointsDTO.getCheckList().get(selectPosition).getPictureUrls();
        if (null != list) {
            list.add(pictureUrlsDTO);
        }
        pointsDTO.getCheckList().get(selectPosition).setPictureUrls(list);
        startWorkAdapter.addImageList(uploadUrl, selectPosition);
        KLog.e("22222-----" + selectPosition + "---" + currentPointPosition);
        //isShowEmpty(selectPosition);

        GetDetailsBean.RecordDTO.PointsDTO.CheckListDTO adapterItem = startWorkAdapter.getItem(selectPosition);
        if (adapterItem.getMustFillRemark() != 0) {
            if (StringUtils.isEmpty(adapterItem.getRemark())) {
                //备注必填 但是没填
                return;
            }
        }

        if (adapterItem.getMustTakePic() != 0) {
            if (adapterItem.getPictureUrls().isEmpty()) {
                //拍照必填 但是没填
                return;
            }
        }

        if (!StringUtils.isEmpty(adapterItem.getCheckResult())) {  //证明当前已经选择了正常 或者异常
            adapterItem.setChecked(1);
        }
        startWorkAdapter.notifyItemChanged(selectPosition);
        EventBus.getDefault().post(new UploadEventLoad());
        startWorkAdapter.notifyDataSetChanged();
    }

    @Override
    public void updatePointSuccess(String type) {
        mRvStart.removeAllViews();
        workOrderId = "";  //本地的workOrderId 重置
        if (pointsDTO.getIsSkip() == 1 && pointsDTO.getStatus().equals("1")) {  //已经跳过了
            //CacheHelper.getInstance().putPointScanMarkers(pointsDTO.getId());
            EventBus.getDefault().post("refresh");
            EventBus.getDefault().post(new HandleJsEvent(EVENT_BUS_NOTIFY_H5_BACK, ""));
            finish();
            return;
        }
        recordType = type;
        switch (type) {
            case "top":
                currentPointPosition = currentPointPosition - 1;
                if (currentPointPosition <= 0) {
                    currentPointPosition = 0;
                }
                iv_all_normal.setSelected(false);
                isAllNormal = false;
                break;
            case "next":
                currentPointPosition = currentPointPosition + 1;
                if (currentPointPosition >= getDetailsBean.getRecord().getPoints().size()) {
                    currentPointPosition = getDetailsBean.getRecord().getPoints().size() - 1;
                }
                iv_all_normal.setSelected(false);
                isAllNormal = false;
                break;
            case "submit":
                EventBus.getDefault().post("refresh");
                onFinish();
                return;
            case "back":
                EventBus.getDefault().post("refresh");
                EventBus.getDefault().post(new HandleJsEvent(EVENT_BUS_NOTIFY_H5_BACK, ""));
                onFinish();
                break;
        }
        if (!isFromFirst) {
            if (getDetailsBean.getRecord().getPoints().get(currentPointPosition).getMustScan().equals("1")
                    && !CacheHelper.getInstance().getPointScanMarkers(pointsDTO.getId())) {
                KLog.e("2222");
                checkScan(ll_base);
                return;
            }
            if (getDetailsBean.getRecord().getPoints().get(currentPointPosition).getMustScan().equals("2")
                    && !CacheHelper.getInstance().getPointScanMarkers(pointsDTO.getId())) {
                KLog.e("2222");
                checkScan(ll_base);
                return;
            }
        }
        KLog.e("222222--" + currentPointPosition);

        if (currentPointPosition >= getDetailsBean.getRecord().getPoints().size()) {
            //证明是跳过的最后一条
            EventBus.getDefault().post("refresh");
            EventBus.getDefault().post(new HandleJsEvent(EVENT_BUS_NOTIFY_H5_BACK, ""));
            onFinish();
            return;
        }

        isClickShutDown = false;
        KLog.e("22222----" + currentPointPosition);
        KLog.e("updateInfo");
        updateInfo();
        //presenter.getRunListPager(assetId, this.type);
    }

    @Override
    public void updatePointFail(HashMap<String, Object> map) {
        String json = new Gson().toJson(map);
        databaseManager.insertInspectPoint(json);
    }

    @Override
    public void getManagerSuccess(GetManagerBean.RecordBean recordBean) {
        managerName = recordBean.getUserName();
        managerPhone = recordBean.getPhone();
        managerId = recordBean.getId();

    }

    @Override
    public void deletePicSuccess(int groupPosition, int position) {
        GetDetailsBean.RecordDTO.PointsDTO.CheckListDTO.PictureUrlsDTO pictureUrlsDTO = startWorkAdapter.getItem(groupPosition).getPictureUrls().get(position);
        List<GetDetailsBean.RecordDTO.PointsDTO.CheckListDTO.PictureUrlsDTO> pictureUrls = startWorkAdapter.getItem(groupPosition).getPictureUrls();
        pictureUrls.remove(pictureUrlsDTO);
        //isShowEmpty(groupPosition);
        startWorkAdapter.notifyItemChanged(groupPosition);
        if (pointsDTO != null) {
            String checkId = pointsDTO.getCheckList().get(selectPosition).getId();
            CacheHelper.getInstance().setImageSuccess(pictureUrlsDTO.getUrl(), checkId);
        }

    }

    View view_bootom;

    private void showAbnormalPopupWindow(View anchor, GetDetailsBean.RecordDTO.PointsDTO.CheckListDTO item, OnAbnormalPopupWindowListener listener) {
        BottomPopupWindow abnormalPopupWindow = new BottomPopupWindow(context, R.layout.dialog_work_error);
        View contentView = abnormalPopupWindow.getContentView();
        TextView tvCancel = contentView.findViewById(R.id.tv_cancel);
        EditText etContent = contentView.findViewById(R.id.et_content);
        TextView tvFontNumber = contentView.findViewById(R.id.tv_font_number);
        LinearLayout ll_work_tick = contentView.findViewById(R.id.ll_work_tick); //报工单
        TextView tv_work_tick_required = contentView.findViewById(R.id.tv_work_tick_required); // 报工单 星号键
        LinearLayout ll_entry_requirement = contentView.findViewById(R.id.ll_entry_requirement); //报单需求
        TextView tv_entry_requirement_required = contentView.findViewById(R.id.tv_entry_requirement_required); //报单需求 星号键
        TextView tv_save_no_declaration = contentView.findViewById(R.id.tv_save_no_declaration); //保存不报单
        view_bootom = contentView.findViewById(R.id.view_bootom);

        GetDetailsBean.RecordDTO.ExceptionReportDTO exceptionReport = getDetailsBean.getRecord().getExceptionReport();
        if (null != exceptionReport) {
            String exceptionReportValue = exceptionReport.getExceptionReport();
            if (!StringUtils.isEmpty(exceptionReportValue)) {
                if (TextUtils.equals("2", exceptionReportValue) || TextUtils.equals("4", exceptionReportValue) || TextUtils.equals("5", exceptionReportValue) || TextUtils.equals("6", exceptionReportValue)) {
                    //报需求单 显示
                    ll_entry_requirement.setVisibility(View.VISIBLE);
                    if ((exceptionReportValue.equals("4") || exceptionReportValue.equals("6")) && StringUtils.isEmpty(item.getWorkOrderId())) {
                        //报需求单显示星号键
                        tv_entry_requirement_required.setVisibility(View.VISIBLE);
                    } else {
                        tv_entry_requirement_required.setVisibility(View.GONE);
                    }
                }

                if (TextUtils.equals("1", exceptionReportValue) || TextUtils.equals("3", exceptionReportValue) || TextUtils.equals("5", exceptionReportValue) || TextUtils.equals("6", exceptionReportValue)) {
                    //报工单 显示
                    ll_work_tick.setVisibility(View.VISIBLE);
                    if ((exceptionReportValue.equals("3") || exceptionReportValue.equals("6")) && StringUtils.isEmpty(item.getWorkOrderId())) {
                        // 报工单 显示 星号键
                        tv_work_tick_required.setVisibility(View.VISIBLE);
                    } else {
                        tv_work_tick_required.setVisibility(View.GONE);
                    }
                }


                if ((!TextUtils.equals("3", exceptionReportValue) && !TextUtils.equals("4", exceptionReportValue) && !TextUtils.equals("6", exceptionReportValue)) || !StringUtils.isEmpty(item.getWorkOrderId())) {
                    //保存不报单显示
                    tv_save_no_declaration.setVisibility(View.VISIBLE);
                    if (!StringUtils.isEmpty(item.getWorkOrderId())) {
                        tv_save_no_declaration.setText(context.getResources().getString(R.string.save));
                    } else {
                        tv_save_no_declaration.setText(context.getResources().getString(R.string.Save_no_declaration));
                    }
                }
            }
        }


        etContent.setText(null == item.getRemark() ? "" : item.getRemark());
        tvCancel.setOnClickListener(v -> {
            abnormalPopupWindow.dismiss();
        });

        etContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @SuppressLint("SetTextI18n")
            @Override
            public void afterTextChanged(Editable s) {
                tvFontNumber.setText(s.length() + "/" + "100");
                if (s.length() > 100) {
                    s.delete(100, s.length());
                }
            }
        });

        ll_work_tick.setOnClickListener(v -> {
            if (StringUtils.isEmpty(etContent.getText().toString())) {
                ToastUtils.showCustomToast(context, R.mipmap.icon_error, getResources().getString(R.string.Please_enter_the_exception_information));
                return;
            }
            listener.onWorkTickClick(etContent.getText().toString(), item.getId(), tv_work_tick_required.getVisibility() == View.VISIBLE);
            abnormalPopupWindow.dismiss();


        });

        tv_save_no_declaration.setOnClickListener(v -> {
            if (StringUtils.isEmpty(etContent.getText().toString())) {
                ToastUtils.showCustomToast(context, R.mipmap.icon_error, getResources().getString(R.string.Please_enter_the_exception_information));
                return;
            }
            listener.OnSaveNoDeclarationClick(etContent.getText().toString());
            abnormalPopupWindow.dismiss();
        });

        ll_entry_requirement.setOnClickListener(v -> {
            if (!NetworkUtils.isAvailable(context)) {
                ToastUtils.showCustomToast(context, R.mipmap.icon_error, getString(R.string.lixianbuyunx));
                return;
            }
            if (StringUtils.isEmpty(etContent.getText().toString())) {
                ToastUtils.showCustomToast(context, R.mipmap.icon_error, getResources().getString(R.string.Please_enter_the_exception_information));
                return;
            }
            listener.onEntryRequirementClick(etContent.getText().toString(), item.getId(), tv_entry_requirement_required.getVisibility() == View.VISIBLE);
            abnormalPopupWindow.dismiss();

        });

        abnormalPopupWindow.show(anchor);
    }


    private void isShowEmpty() {
        if (startWorkAdapter == null) return;
        int count = 0;
        boolean isShow;
        for (int i = 0; i < startWorkAdapter.getData().size(); i++) {
            if (startWorkAdapter.getData().get(i).getChecked() == 1) {
                count++;
            }
        }
        if (isShowUnChane) {
            if (count == startWorkAdapter.getData().size()) {
                ll_empty.setVisibility(View.VISIBLE);
                mRvStart.setVisibility(View.GONE);
            } else {
                ll_empty.setVisibility(View.GONE);
                mRvStart.setVisibility(View.VISIBLE);
            }
        } else {
            ll_empty.setVisibility(View.GONE);
            mRvStart.setVisibility(View.VISIBLE);
        }

    }


    public interface OnAbnormalPopupWindowListener {
        void OnSaveNoDeclarationClick(String content);

        void onWorkTickClick(String content, String InspectionItemId, boolean isMust);

        void onEntryRequirementClick(String content, String InspectionItemId, boolean isMust);
    }

    public void uploadVideo(final String localUrl, String ids) {
        File files = new File(localUrl);
        if (!files.exists()) {
            return;
        }
//        loadingDialog.setText(getResources().getString(R.string.uploading));
        showLoading();
        presenter.uploadVideo(localUrl, ids, files);
    }


    @Override
    public void uploadVideoError(String url, String ids) {
        hideLoading();
        GetDetailsBean.RecordDTO.PointsDTO.CheckListDTO.PictureUrlsDTO pictureUrlsDTO = new GetDetailsBean.RecordDTO.PointsDTO.CheckListDTO.PictureUrlsDTO();
        pictureUrlsDTO.setUrl(url);
        pictureUrlsDTO.setId(ids);
        pictureUrlsDTO.setThumburl(url);
        List<GetDetailsBean.RecordDTO.PointsDTO.CheckListDTO.PictureUrlsDTO> list = pointsDTO.getCheckList().get(selectPosition).getPictureUrls();
        if (null != list) {
            list.add(pictureUrlsDTO);
        }
        pointsDTO.getCheckList().get(selectPosition).setPictureUrls(list);
        startWorkAdapter.addVideoList(url, selectPosition);
        //isShowEmpty(selectPosition);
        startWorkAdapter.notifyItemChanged(selectPosition);
        //存到数据库
        Map<String, Object> map = new HashMap<>();
        map.put("ids", ids);
        map.put("url", url);
        String pointPosition = getDetailsBean.getRecord().getPoints().get(currentPointPosition).getId();
        map.put("point", pointPosition);
        map.put("des", getDetailsBean.getRecord().getPoints().get(currentPointPosition).getAssetDesc());
        String json = new Gson().toJson(map);
        databaseManager.insertInspectPic(json);


    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(StartH5Event event) {
        if (event == null) return;
        String json = event.getJson();
        KLog.e(json);
        if (!StringUtils.isEmpty(json)) {
            try {
                KLog.e("2222" + json);
                JSONObject jsonObject = new JSONObject(json);
                if (jsonObject.has("checkId")) {
                    String checkId = jsonObject.getString("checkId");
                    if (jsonObject.has("orderId")) {
                        String orderId = jsonObject.getString("orderId");
                        workOrderId = orderId;
                        Log.e("longlonglong", workOrderId);
                        for (int i = 0; i < startWorkAdapter.getData().size(); i++) {
                            if (startWorkAdapter.getData().get(i).getId().equals(checkId)) {
                                startWorkAdapter.getData().get(i).setWorkOrderId(orderId);
                                break;
                            }
                        }

                    }
                }
                if (null != recordItem && recordPosition != -1) {
                    if (recordItem.getHasMeter() == 1) {
                        recordItem.setAbnormal(1);
                    } else {
                        recordItem.setAbnormal(1);
                        recordItem.setCheckResult("N1");
                    }

                    if ((recordItem.getMustFillRemark() != 0 && StringUtils.isEmpty(recordItem.getRemark())) ||
                            (recordItem.getMustTakePic() != 0 && recordItem.getPictureUrls().isEmpty())) {
                        recordItem.setChecked(0);
                    } else {
                        recordItem.setChecked(1);
                    }
                    startWorkAdapter.notifyItemChanged(recordPosition);
                    recordItem = null;
                    recordPosition = -1;
                }

            } catch (JSONException e) {
                throw new RuntimeException(e);
            }
        }


    }


}
